如何在ASP.NET WebAPI中返回文件(FileContentResult)在常规的MVC控制器中,我们可以用a输出pdf FileContentResult。public FileContentResult Test(TestViewModel vm){
var stream = new MemoryStream();
//... add content to the stream.
return File(stream.GetBuffer(), "application/pdf", "test.pdf");}但是我们怎样才能把它变成一个ApiController?[HttpPost]public IHttpActionResult Test(TestViewModel vm){
//...
return Ok(pdfOutput);}这是我尝试过但它似乎不起作用。[HttpGet]public IHttpActionResult Test(){
var stream = new MemoryStream();
//...
var content = new StreamContent(stream);
content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
content.Headers.ContentLength = stream.GetBuffer().Length;
return Ok(content); }浏览器中显示的返回结果为:{"Headers":[{"Key":"Content-Type","Value":["application/pdf"]},{"Key":"Content-Length","Value":["152844"]}]}有什么建议?
3 回答
杨__羊羊
TA贡献1943条经验 获得超7个赞
所以,试试这个:
控制器代码:
[HttpGet]public HttpResponseMessage Test(){ var path = System.Web.HttpContext.Current.Server.MapPath("~/Content/test.docx");; HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); var stream = new FileStream(path, FileMode.Open); result.Content = new StreamContent(stream); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = Path.GetFileName(path); result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentLength = stream.Length; return result; }
查看Html标记(使用click事件和简单URL):
<script type="text/javascript"> $(document).ready(function () { $("#btn").click(function () { // httproute = "" - using this to construct proper web api links. window.location.href = "@Url.Action("GetFile", "Data", new { httproute = "" })"; }); });</script><button id="btn"> Button text</button><a href=" @Url.Action("GetFile", "Data", new { httproute = "" }) ">Data</a>
- 3 回答
- 0 关注
- 8510 浏览
添加回答
举报
0/150
提交
取消