【发布时间】:2020-05-27 13:30:19
【问题描述】:
我正在尝试从字节数组下载文件,但提示似乎没有进行下载。我是否需要包含额外的 ContentDisposition 属性?如果我查看 IE 中的网络流量,我可以看到文件请求有效并且返回 200,此外我还可以从 IE 调试工具内容下载文件。
字节数组中存储的文件是Word文档。我已将 mime 类型设置为:
application/vnd.openxmlformats-officedocument.wordprocessingml.document
文档文件名为:QuickStartGuide.docx
以及为什么没有显示下载提示?
[HttpPost]
[ValidateAntiForgeryToken]
public FileContentResult DocumentDownload(int documentId)
{
try
{
var document = BusinessLayer.GetDocumentsByDocument(documentId, AuthenticationHandler.HostProtocol).FirstOrDefault();
System.Net.Mime.ContentDisposition contentDisposition = new System.Net.Mime.ContentDisposition();
contentDisposition.FileName = document.FileName;
contentDisposition.Inline = false;
var result = new FileContentResultWithContentDisposition(document.FileBytes, document.FileType, contentDisposition);
return result;
}
catch
{
throw;
}
}
public class FileContentResultWithContentDisposition : FileContentResult
{
private const string ContentDispositionHeaderName = "Content-Disposition";
public FileContentResultWithContentDisposition(byte[] fileContents, string contentType, ContentDisposition contentDisposition)
: base(fileContents, contentType)
{
// check for null or invalid ctor arguments
ContentDisposition = contentDisposition;
}
public ContentDisposition ContentDisposition { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
// check for null or invalid method argument
ContentDisposition.FileName = ContentDisposition.FileName ?? FileDownloadName;
var response = context.HttpContext.Response;
response.ContentType = ContentType;
response.AddHeader(ContentDispositionHeaderName, ContentDisposition.ToString());
WriteFile(response);
}
}
【问题讨论】:
标签: c# .net asp.net-mvc-5