我找到了这个链接。 ASP.NET MVC download image rather than display in browser
我尝试了所有内容,我的操作方法将文件转储到视图中而不是下载。我希望能够单独下载该文件。感谢
if (extension.ToLower() == ".docx")
{ // Handle *.jpg and
contentType = "application/docx";
}
else if (extension.ToLower() == ".jpg")
{// Handle *.gif
contentType = "image/jpeg jpeg jpg jpe";
}
else if (extension.ToLower() == ".pdf")
{// Handle *.pdf
contentType = "application/pdf";
}
Response.ContentType = contentType; // "application/force-download";
Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.WriteFile(FilePath );
Response.Flush();
Response.End();[![View after clicking download button][1]][1]
答案 0 :(得分:0)
您的问题可能类似于:
How can I present a file for download from an MVC controller?
Returning a file to View/Download in ASP.NET MVC
您可以使用此代码从操作方法返回Response.WriteFile
或FileResult
,而不是使用FileStreamResult
:
if (extension.ToLower() == ".docx")
{ // Handle *.jpg and
contentType = "application/docx";
}
else if (extension.ToLower() == ".jpg")
{// Handle *.gif
contentType = "image/jpeg jpeg jpg jpe";
}
else if (extension.ToLower() == ".pdf")
{// Handle *.pdf
contentType = "application/pdf";
}
Response.ContentType = contentType; // "application/force-download";
Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
// returning the file for download as FileResult
// third input parameter is optional
return File(FileName, contentType, Server.UrlEncode(Filename));
注意:正如Leo在https://stackoverflow.com/a/36776089/6378815中所说,如果响应标头已包含Response.AppendHeader
部分,Content-Disposition
方法可能会导致浏览器无法呈现文件内容。您可能需要尝试这种方式:
Response.Headers.Add("Content-Disposition", "attachment; filename=" + FileName);
补充参考: