我有带表单的Asp.Net MVC Web应用程序。当我提交表单应用程序运行方法时:
[HttpPost]
public ActionResult MyMethod(MyViewModel model)
{
FileStreamResult document = CreateDocument(model);
return document;
}
浏览器会在同一选项卡中打开生成的文件(PDF)。我不想打开该文件,而是想将其下载到磁盘。如何执行此动作?
您需要告诉浏览器它是下载文件,而不是文件。
您可以通过设置2个标题(内容类型和内容处置),然后将PDF写入响应流来实现。
[HttpPost]
public ActionResult MyMethod(MyViewModel model)
{
HttpResponseBase response = ControllerContext.HttpContext.Response;
response.ContentType = "application/pdf";
response.AppendHeader("Content-Disposition", "attachment;filename=yourpdf.pdf");
FileStreamResult document = CreateDocument(model);
//Write you document to response.OutputStream here
document.FileStream.Seek(0, SeekOrigin.Begin);
document.FileStream.CopyTo(response.OutputStream, document.FileStream.Length);
response.Flush();
return new EmptyResult();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句