通用 模拟下载文件保存方法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通用 模拟下载文件保存方法相关的知识,希望对你有一定的参考价值。
起始:
需要使用weiapi 请求外部接口获取文件并保存。
使用方法:
使用
WebRequest 模拟Http请求 获取返回流 。
发现问题:
本地搭建webapi模拟外接口测试时发现,无法获取到webapi返回的文件流。
解决方法:
修改方法。使用httpclient,得到返回的 httpresponsemessage。
经过测试发现,可以兼容各种返回结果。
代码重现:
请求地址的代码: string filePath = "d:333.xls"; try { var stream = new FileStream(filePath, FileMode.Open); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StreamContent(stream); response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "333.xls" }; return response; } catch { return new HttpResponseMessage(HttpStatusCode.NoContent); }
使用HttpRequest模拟请求接收:
HttpWebRequest request = WebRequest.Create(Url) as HttpWebRequest; HttpWebResponse response = request.GetResponse() as HttpWebResponse; string file = "xxx"; //获取文件名 Stream responseStream = response.GetResponseStream(); //创建本地文件写入流 Stream stream = new FileStream(file, FileMode.Create); byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, (int)bArr.Length); while (size > 0) { stream.Write(bArr, 0, size); size = responseStream.Read(bArr, 0, (int)bArr.Length); } stream.Close(); responseStream.Close();
使用HttpClient模拟请求接收:
//用 request 没法获取到文件流 改用client HttpResponseMessage responseMessage = new HttpResponseMessage(); using (HttpClient httpClient = new HttpClient()) { Task<HttpResponseMessage> responseMessageTask = httpClient.GetAsync(Url); responseMessage = responseMessageTask .Result; } string file = ""; //生成文件名和路径 Stream stream = new FileStream(file, FileMode.Create); var responseStream = responseMessage .Content.ReadAsStreamAsync().Result; byte[] bArr = new byte[1024]; int size = responseStream.Read(bArr, 0, (int)bArr.Length); while (size > 0) { stream.Write(bArr, 0, size); size = responseStream.Read(bArr, 0, (int)bArr.Length); } responseStream.Close(); stream.Close();
以上是关于通用 模拟下载文件保存方法的主要内容,如果未能解决你的问题,请参考以下文章