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

Gui*_*ngo 6 javascript c# asp.net asp.net-mvc asp.net-mvc-4

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

视图:

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

控制器:

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

Fel*_*ani 8

我认为您无法在浏览器中下载异步文件,只需将用户重定向到该操作,浏览器将打开一个保存对话框窗口.在asp.net mvc中,您可以使用一种操作方法来下载文件,从而生成基本控制器FileResultFile方法.

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");
}
Run Code Online (Sandbox Code Playgroud)

  • 这取决于浏览器.如果您设置为自动下载到给定文件夹,浏览器将自动下载.Firefox和Chrome是一些具有此行为的浏览器. (3认同)
  • 它会自动下载,无需询问。对话框不显示! (2认同)