菜的像徐坤
排名
7
文章
192
粉丝
15
评论
16
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术

文件流下载(winfrom)

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

前言

下载api中返回的文件里

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

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

  1.   string defaultPath = "";
  2.  private void button1_Click(object sender, EventArgs e)
  3.         {
  4.             FolderBrowserDialog fbd = new FolderBrowserDialog();
  5.             fbd.Description = "请选择文件下载地址";
  6.             //首次defaultPath为空,按FolderBrowserDialog默认设置(即桌面)选择  
  7.             if (defaultPath != "")
  8.             {
  9.                 //设置此次默认目录为上一次选中目录  
  10.                 fbd.SelectedPath = defaultPath;
  11.             }
  12.             //按下确定选择的按钮  
  13.             if (fbd.ShowDialog() == DialogResult.OK)
  14.             {
  15.                 //记录选中的目录  
  16.                 defaultPath = fbd.SelectedPath;
  17.             }
  18.            
  19.         }

具体实现(下载的方法)

  1.         /// <summary>
  2.         /// 下载
  3.         /// </summary>
  4.         /// <param name="jsonStr"></param>
  5.         /// <returns></returns>
  6.         public string selectAPI(string jsonStr)
  7.         {
  8.             //下载的api
  9.             string url = "http://10.72.3.0:8086/CSB";
  10.             string result = "";//返回结果
  11.             try
  12.             {
  13.                 Encoding encoding = Encoding.UTF8;
  14.                 HttpWebResponse response;
  15.                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址
  16.                 request.Accept = "text/html,application/xhtml+xml,*/*";
  17.                 request.ContentType = "application/json";
  18.                 //请求方式
  19.                 request.Method = "POST";
  20.                 //头文件
  21.                 request.Headers.Add("_api_timestamp""1623325847266");
  22.                 request.Headers.Add("_api_name""hssServives");
  23.                 request.Headers.Add("_api_version""1.0.0");
  24.                 request.Headers.Add("_api_access_key""3b78a66b1bb04183a0215b7b8e6e18e9");
  25.                 request.Headers.Add("_api_signature""AYbcuYagEwhnbf+zr4CjVhqSRPs=");
  26.                 try
  27.                 {
  28.                     byte[] payload;
  29.                     //将URL编码后的字符串转化为字节
  30.                     payload = System.Text.Encoding.UTF8.GetBytes(jsonStr);
  31.                     //设置请求的 ContentLength 
  32.                     request.ContentLength = payload.Length;
  33.                     //获得请 求流
  34.                     System.IO.Stream writer = request.GetRequestStream();
  35.                     //将请求参数写入流
  36.                     writer.Write(payload, 0, payload.Length);
  37.                     // 关闭请求流
  38.                     writer.Close();
  39.                     response = (HttpWebResponse)request.GetResponse();
  40.                 }
  41.                 catch (WebException ex)
  42.                 {
  43.                     response = (HttpWebResponse)ex.Response;
  44.                 }
  45.                 using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
  46.                 {
  47.                     //返回的流文件
  48.                     Stream stream = response.GetResponseStream();
  49.                     //将基础流写入内存流(手动转换流)
  50.                     MemoryStream memoryStreams = StreamToMemoryStream(stream);
  51.                     byte[] srcBuf = new Byte[memoryStreams.Length];
  52.                     memoryStreams.Read(srcBuf, 0, srcBuf.Length);
  53.                     memoryStreams.Seek(0, SeekOrigin.Begin);
  54.                     //配置文件名
  55.                     defaultPath = defaultPath + @"\\" + Guid.NewGuid().ToString().Replace("-""") + ".zip";
  56.                     using (FileStream fs = new FileStream(defaultPath, FileMode.Create, FileAccess.Write))
  57.                     {
  58.                         fs.Write(srcBuf, 0, srcBuf.Length);
  59.                         fs.Close();
  60.                     }
  61.                 }
  62.                 if (response.StatusCode != HttpStatusCode.OK)//返回响应码非成功格式化数据后返回
  63.                 {
  64.                     result = "Exception:" + result;
  65.                 }
  66.                 return result;
  67.             }
  68.             catch (WebException ex)
  69.             {
  70.                 return "Exception:" + ex.Message;
  71.             }
  72.         }

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

  1.  public MemoryStream StreamToMemoryStream(Stream stream)
  2.         {
  3.             MemoryStream memoryStream = new MemoryStream();
  4.             //将基础流写入内存流
  5.             const int bufferLength = 1024;
  6.             byte[] buffer = new byte[bufferLength];
  7.             int actual = stream.Read(buffer, 0, bufferLength);
  8.             while (actual > 0)
  9.             {
  10.                 // 读、写过程中,流的位置会自动走。
  11.                 memoryStream.Write(buffer, 0, actual);
  12.                 actual = stream.Read(buffer, 0, bufferLength);
  13.             }
  14.             memoryStream.Position = 0;
  15.             return memoryStream;
  16.         }


评价