WebAPI实现文件下载功能
作者:互联网
在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;
}
}
标签:WebAPI,文件,billInfoID,httpResponseMessage,Content,Headers,ms,new,下载 来源: https://www.cnblogs.com/hkfyf/p/11857897.html