菜的像徐坤
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术

文件流下载(winfrom)

4947人阅读 2021/10/14 11:29 总访问:882927 评论:0 收藏:0 手机
分类: 文件流

前言

下载api中返回的文件里

与web端不同,winfrom 不能使用Responses与 Request
所以下载需要换种方式(核心是怎么拿到返回的流文件)

具体实现(选择保存地址)

  string defaultPath = "";
 private void button1_Click(object sender, EventArgs e)
        {

            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.Description = "请选择文件下载地址";
            //首次defaultPath为空,按FolderBrowserDialog默认设置(即桌面)选择  
            if (defaultPath != "")
            {
                //设置此次默认目录为上一次选中目录  
                fbd.SelectedPath = defaultPath;
            }
            //按下确定选择的按钮  
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                //记录选中的目录  
                defaultPath = fbd.SelectedPath;
            }
           
        }

具体实现(下载的方法)

        /// <summary>
        /// 下载
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public string selectAPI(string jsonStr)
        {
            //下载的api
            string url = "http://10.72.3.0:8086/CSB";
            string result = "";//返回结果
            try
            {
                Encoding encoding = Encoding.UTF8;
                HttpWebResponse response;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址

                request.Accept = "text/html,application/xhtml+xml,*/*";
                request.ContentType = "application/json";
                //请求方式
                request.Method = "POST";
                //头文件
                request.Headers.Add("_api_timestamp", "1623325847266");
                request.Headers.Add("_api_name", "hssServives");
                request.Headers.Add("_api_version", "1.0.0");
                request.Headers.Add("_api_access_key", "3b78a66b1bb04183a0215b7b8e6e18e9");
                request.Headers.Add("_api_signature", "AYbcuYagEwhnbf+zr4CjVhqSRPs=");

                try
                {
                    byte[] payload;
                    //将URL编码后的字符串转化为字节
                    payload = System.Text.Encoding.UTF8.GetBytes(jsonStr);
                    //设置请求的 ContentLength 
                    request.ContentLength = payload.Length;
                    //获得请 求流
                    System.IO.Stream writer = request.GetRequestStream();
                    //将请求参数写入流
                    writer.Write(payload, 0, payload.Length);
                    // 关闭请求流
                    writer.Close();
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException ex)
                {
                    response = (HttpWebResponse)ex.Response;
                }
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    //返回的流文件
                    Stream stream = response.GetResponseStream();
                    //将基础流写入内存流(手动转换流)
                    MemoryStream memoryStreams = StreamToMemoryStream(stream);
                    byte[] srcBuf = new Byte[memoryStreams.Length];
                    memoryStreams.Read(srcBuf, 0, srcBuf.Length);
                    memoryStreams.Seek(0, SeekOrigin.Begin);
                    //配置文件名
                    defaultPath = defaultPath + @"\\" + Guid.NewGuid().ToString().Replace("-", "") + ".zip";
                    using (FileStream fs = new FileStream(defaultPath, FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(srcBuf, 0, srcBuf.Length);
                        fs.Close();
                    }
                }
                if (response.StatusCode != HttpStatusCode.OK)//返回响应码非成功格式化数据后返回
                {
                    result = "Exception:" + result;
                }
                return result;
            }
            catch (WebException ex)
            {
                return "Exception:" + ex.Message;
            }
        }

具体实现(将基础流写入内存流的方法)

 public MemoryStream StreamToMemoryStream(Stream stream)
        {
            MemoryStream memoryStream = new MemoryStream();

            //将基础流写入内存流
            const int bufferLength = 1024;
            byte[] buffer = new byte[bufferLength];
            int actual = stream.Read(buffer, 0, bufferLength);
            while (actual > 0)
            {
                // 读、写过程中,流的位置会自动走。
                memoryStream.Write(buffer, 0, actual);
                actual = stream.Read(buffer, 0, bufferLength);
            }
            memoryStream.Position = 0;

            return memoryStream;
        }


评价