如何在ASP.NET MVC 4中显示打开/保存对话框

6
我可以请求文件并将其返回,但我不知道如何显示打开/保存对话框。
视图:
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();
}
2个回答

8

我认为您无法在浏览器异步下载文件,只需将用户重定向到操作并让浏览器打开保存对话框窗口。在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");
}

2
它在没有询问的情况下自动下载。对话框没有显示! - Guilherme Longo
3
这取决于浏览器。如果您将其设置为自动下载到特定文件夹,浏览器会自动下载。Firefox和Chrome是具有此行为的一些浏览器。 - João Simões
@JoãoSimões 有没有办法让“另存为对话框”在Firefox和Chrome中出现?我还在寻找解决方案! - Shubh
1
对于Chrome浏览器:在设置中,点击“显示高级设置”,然后向下滚动到“下载”部分。要更改默认下载位置,请单击“更改”并选择您希望保存文件的位置。如果您更愿意为每个下载选择特定位置,则选择“在下载前询问每个文件的保存位置”的复选框。 - jaybro
对于Firefox:https://support.mozilla.org/zh-CN/kb/change-firefox-behavior-when-open-file - jaybro

1

强制 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");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接