首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我的MVC视图将文件内容显示到视图中,而不是作为文件下载

我的MVC视图将文件内容显示到视图中,而不是作为文件下载
EN

Stack Overflow用户
提问于 2016-10-13 03:58:26
回答 1查看 637关注 0票数 0

我找到了这个链接。ASP.NET MVC download image rather than display in browser

我尝试了所有方法,我的action方法将文件转储到视图中,而不是下载。我希望能够单独下载该文件。谢谢

代码语言:javascript
复制
        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]
EN

回答 1

Stack Overflow用户

发布于 2016-10-13 09:31:46

您的问题可能与以下问题类似:

How can I present a file for download from an MVC controller?

Returning a file to View/Download in ASP.NET MVC

您可以使用以下代码从操作方法返回FileResultFileStreamResult,而不是使用Response.WriteFile

代码语言:javascript
复制
    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));

您可能希望这样尝试:

代码语言:javascript
复制
Response.Headers.Add("Content-Disposition", "attachment; filename=" + FileName);

其他参考资料:

Response.WriteFile() -- not working asp net mvc 4.5

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40007286

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档