javascript 如何显示打开/保存对话框 asp net mvc 4

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14139316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:49:34  来源:igfitidea点击:

How to display open/save dialog asp net mvc 4

c#javascriptasp.netasp.net-mvcasp.net-mvc-4

提问by Guilherme Longo

I am able to request a file and also have it returned. I don′t know how to display a open/save dialog box.

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

View:

看法:

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

Controller:

控制器:

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

回答by Felipe Oriani

I think you cannot download a file in a browser async, just redirect the user to the action and the browser will open a save dialog window. In asp.net mvc you could have an action method to download a file resulting in a FileResultwith the Filemethod of the base controller.

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

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

回答by Zaphod

One way to force firefox (doen't work for chrome) to open the save dialogue is to set the contenttype to "application/octet-stream" and give it a filename with the correct extension.

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