Web Api通过文件流下载文件到本地实例
最近项目里面需要和C++的客户端互动,其中一个接口就是需要提供文件下载的接口,保证C++项目调用这个接口的时候能够正常下载文件到本地。参考了一下网上的代码,其原理就是读取服务器上指定路径的文件流,并将文件流包装成返回的HttpResponseMessage的StreamContent。具体实现代码如下:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Http; namespace WebAPI.Controllers { public class DownloadFileController : ApiController { /// <summary> /// 从WebAPI下载文件 /// </summary> /// <returns></returns> public IHttpActionResult GetFileFromWebApi() { var browser = String.Empty; if (HttpContext.Current.Request.UserAgent != null) { browser = HttpContext.Current.Request.UserAgent.ToUpper(); } string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Content", "标准事件.png"); HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK); FileStream fileStream = File.OpenRead(filePath); httpResponseMessage.Content = new StreamContent(fileStream); httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = browser.Contains("FIREFOX") ? Path.GetFileName(filePath) : HttpUtility.UrlEncode(Path.GetFileName(filePath)) //FileName = HttpUtility.UrlEncode(Path.GetFileName(filePath)) }; return ResponseMessage(httpResponseMessage); } } }
实现以上控制器后,我们可以直接在浏览器中请求这个api的地址(示例中的地址为:localhost:55603/api/DownloadFile/GetFileFromWebApi),即可弹出下载文件的对话框了,如图: