ASP.NET MVC下载图像而不是在浏览器中显示

RSo*_*erg 35 c# asp.net-mvc controller image download

我不想在浏览器窗口中显示PNG,而是希望操作结果触发文件下载对话框(您知道打开,另存为等).我可以使用未知的内容类型来使用下面的代码,但是用户必须在文件名的末尾键入.png.如何在不强制用户输入文件扩展名的情况下完成此行为?

    public ActionResult DownloadAdTemplate(string pathCode)
    {
        var imgPath = Server.MapPath(service.GetTemplatePath(pathCode));
        return base.File(imgPath, "application/unknown");
    }
Run Code Online (Sandbox Code Playgroud)

解....

    public ActionResult DownloadAdTemplate(string pathCode)
    {
        var imgPath = Server.MapPath(service.GetTemplatePath(pathCode));
        Response.AddHeader("Content-Disposition", "attachment;filename=DealerAdTemplate.png");
        Response.WriteFile(imgPath);
        Response.End();
        return null;
    }
Run Code Online (Sandbox Code Playgroud)

wom*_*omp 42

我相信您可以使用content-disposition标头来控制它.

Response.AddHeader(
       "Content-Disposition", "attachment; filename=\"filenamehere.png\""); 
Run Code Online (Sandbox Code Playgroud)


Are*_*ren 9

您需要在响应上设置以下标头:

  • Content-Disposition: attachment; filename="myfile.png"
  • Content-Type: application/force-download


Pau*_*zke 5

我实际上来到这里是因为我正在寻找相反的效果.

    public ActionResult ViewFile()
    {
        string contentType = "Image/jpeg";



        byte[] data = this.FileServer("FileLocation");

        if (data == null)
        {
            return this.Content("No picture for this program.");
        }

        return File(data, contentType, img + ".jpg");
    }
Run Code Online (Sandbox Code Playgroud)