相关疑难解决方法(0)

将文件返回到ASP.NET MVC中的查看/下载

我在ASP.NET MVC中将存储在数据库中的文件发送回用户时遇到问题.我想要的是一个列出两个链接的视图,一个用于查看文件并让发送给浏览器的mimetype确定应该如何处理,另一个用于强制下载.

如果我选择查看调用的文件SomeRandomFile.bak并且浏览器没有关联的程序来打开这种类型的文件,那么我没有问题,它默认为下载行为.但是,如果我选择查看调用的文件,SomeRandomFile.pdf或者SomeRandomFile.jpg我希望文件只是打开.但是我也希望将下载链接保留在一边,这样无论文件类型如何,我都可以强制下载提示.这有意义吗?

我已经尝试过FileStreamResult它适用于大多数文件,它的构造函数默认不接受文件名,因此根据url(根据内容类型不知道要提供的扩展名)为未知文件分配文件名.如果我通过指定强制文件名,我将失去浏览器直接打开文件的能力,我得到一个下载提示.有人遇到过这种情况么.

这些是我迄今为止尝试过的例子.

//Gives me a download prompt.
return File(document.Data, document.ContentType, document.Name);
Run Code Online (Sandbox Code Playgroud)

//Opens if it is a known extension type, downloads otherwise (download has bogus name and missing extension)
return new FileStreamResult(new MemoryStream(document.Data), document.ContentType);
Run Code Online (Sandbox Code Playgroud)

//Gives me a download prompt (lose the ability to open by default if known type)
return new FileStreamResult(new MemoryStream(document.Data), document.ContentType) {FileDownloadName = document.Name};
Run Code Online (Sandbox Code Playgroud)

有什么建议?

c# asp.net-mvc download http-headers asp.net-mvc-3

284
推荐指数
5
解决办法
33万
查看次数

HTTP响应头中内容处置的使用

我发现以下asp.net代码在从数据库提供文件时非常有用:

Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);
Run Code Online (Sandbox Code Playgroud)

这允许用户将文件保存到他们的计算机,然后决定如何使用它,而不是尝试使用该文件的浏览器.

使用内容处置响应标头还可以做些什么?

http httpresponse httpwebresponse content-disposition http-headers

122
推荐指数
4
解决办法
21万
查看次数

从 byte[] 下载文件 C# MVC

我正在尝试从字节数组下载文件,但提示似乎没有进行下载。我需要包含额外的 ContentDisposition 属性吗?如果我查看 IE 中的网络流量,我可以看到文件请求有效并且返回 200,此外我还可以从 IE 调试工具内容下载文件。

存储在字节数组中的文件是一个 Word 文档。我已将 MIME 类型设置为:

应用程序/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)
    {
        // …
Run Code Online (Sandbox Code Playgroud)

.net c# asp.net-mvc-5

2
推荐指数
1
解决办法
2万
查看次数