【问题标题】:How to display open/save dialog asp net mvc 4如何显示打开/保存对话框 asp net mvc 4
【发布时间】:2012-12-17 20:08:39
【问题描述】:

我可以请求一个文件并将其返回。 我不知道如何显示打开/保存对话框。

查看:

function saveDocument() {
    $.ajax({
        url: '/Operacao/saveDocument',
        type: 'POST',
        DataType: "html",
        success: function (data) {
            //I get the file content here
        }
    });
}

控制器:

public void saveDocument() {
    Response.ContentType = "image/jpeg";
    Response.AppendHeader("Content-Disposition", "attachment; filename=SailBig.jpg");
    Response.TransmitFile(Server.MapPath("~/MyPDFs/Pdf1.pdf"));    
    Response.End();
}

【问题讨论】:

    标签: c# javascript asp.net asp.net-mvc asp.net-mvc-4


    【解决方案1】:

    我认为您不能在浏览器中异步下载文件,只需将用户重定向到操作,浏览器就会打开一个保存对话框窗口。在 asp.net mvc 中,您可以使用基本控制器的 File 方法下载文件并生成 FileResult 的操作方法。

    public ActionResult SaveDocument()
    {   
        string filePath = Server.MapPath("~/MyPDFs/Pdf1.pdf");
        string contentType = "application/pdf";
    
        //Parameters to file are
        //1. The File Path on the File Server
        //2. The content type MIME type
        //3. The parameter for the file save by the browser
    
        return File(filePath, contentType, "Report.pdf");
    }
    

    【讨论】:

    • 不询问就自动下载。对话框不显示!
    • 这取决于浏览器。如果您设置自动下载到给定文件夹,浏览器将自动下载。 Firefox 和 Chrome 是一些具有这种行为的浏览器。
    • 感谢您的关注!
    • @JoãoSimões 有没有办法让get Save As dialogue box 出现在 Firefox 和 Chrome 中?我还在寻找解决方案!
    • 对于 Chrome:在“设置”中,单击“显示高级设置”并向下滚动到“下载”部分。要更改默认下载位置,请单击更改并选择您希望保存文件的位置。如果您希望为每次下载选择一个特定位置,请选中“下载前询问每个文件的保存位置”复选框。
    【解决方案2】:

    强制 firefox(不适用于 chrome)打开保存对话框的一种方法是将内容类型设置为“application/octet-stream”,并为其指定具有正确扩展名的文件名。

    public ActionResult SaveDocument()
    {   
        string filePath = Server.MapPath("~/MyPDFs/Pdf1.pdf");
        string contentType = "application/octet-stream";  //<---- This is the magic
    
        //Parameters to file are
        //1. The File Path on the File Server
        //2. The content type MIME type
        //3. The parameter for the file save by the browser
    
        return File(filePath, contentType, "Report.pdf");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-12
      • 2020-06-21
      • 1970-01-01
      相关资源
      最近更新 更多