代码之家  ›  专栏  ›  技术社区  ›  RSolberg

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

  •  35
  • RSolberg  · 技术社区  · 14 年前

    我希望操作结果触发文件下载对话框(您知道open、save as等),而不是在浏览器窗口中显示PNG。我可以使用一个未知的内容类型来处理下面的代码,但是用户必须在文件名的末尾键入.png。如何在不强制用户键入文件扩展名的情况下实现此行为?

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

    解决方案。。。。

        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;
        }
    
    6 回复  |  直到 14 年前
        1
  •  42
  •   The Matt    14 年前

    我相信您可以通过content-disposition头来控制这一点。

    Response.AddHeader(
           "Content-Disposition", "attachment; filename=\"filenamehere.png\""); 
    
        2
  •  10
  •   Aren    14 年前

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

    • Content-Disposition: attachment; filename="myfile.png"
    • Content-Type: application/force-download
        3
  •  5
  •   Paul Totzke    12 年前

    其实我来这里是因为我在寻找相反的效果。

        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");
        }
    
        4
  •  3
  •   Iain M Norman    11 年前

    FileResult 并返回一个 FilePathResult

    public FileResult ImageDownload(int id)
        {
            var image = context.Images.Find(id);
            var imgPath = Server.MapPath(image.FilePath);
            return File(imgPath, "image/jpeg", image.FileName);
        }
    
        5
  •  2
  •   NoWar    10 年前

    FileResult 班级。

     public FileResult DownloadFile(string id)
    {
    try
    {
        byte[] imageBytes =  ANY IMAGE SOURCE (PNG)
        MemoryStream ms = new MemoryStream(imageBytes);
        var image = System.Drawing.Image.FromStream(ms);
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        var fileName = string.Format("{0}.png", "ANY GENERIC FILE NAME");
        return File(ms.ToArray(), "image/png", fileName);
    }
    catch (Exception)
    {
    }
    return null;
    }
    
        6
  •  1
  •   user714055 user714055    11 年前

    这个我其实@7072k3

    var result = File(path, mimeType, fileName);
    Response.ContentType = mimeType;
    Response.AddHeader("Content-Disposition", "inline");
    return result;
    

    从我的工作代码中复制的。 这仍然使用标准的ActionResult返回类型。