WebAPI实现文件下载功能

夙愿已清 提交于 2019-12-04 11:25:24

在WebAPI控制器下返回一个HttpResponseMessage对象,设置相应的内容即可。

Content = new StreamContent(ms)//要返回的流,任意Stream的派生类实例对象即可,注意在StreamMemory中,要把下标归到流的开始,如     ms.Seek(0, SeekOrigin.Begin);其中ms是一个StreamMemory实例对象,否则会造成读取的内容不完整

httpResponseMessage.Content.Headers.ContentType= new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");//这里说明返回的是一个二进制流;

httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = $"{billInfoID}.xls" };//返回的文件的类型及文件名


设置的响应头中的内容,只是按一个标准设置的,其目的是方便客户端识别信息,到底是什么内容由你传的流确定。


EX:

public HttpResponseMessage ExportBill(Guid billInfoID)
     {
         Stream ms = null;
         try
         {
             ms = _HTBillInfoLogic.ExportBillInfo(billInfoID);
             ms.Seek(0, SeekOrigin.Begin);
         }
         catch(Exception e)
         {
             throw e;
         }

        HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK)
         {
             Content = new StreamContent(ms)
         };
         httpResponseMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
         httpResponseMessage.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = $"{billInfoID}.xls" };

        return httpResponseMessage;
     }
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!