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();
}
4

2 回答 2

8

我认为您不能在浏览器中异步下载文件,只需将用户重定向到操作,浏览器就会打开一个保存对话框窗口。在 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");
}
于 2013-01-03T12:55:49.103 回答
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");
}
于 2013-11-22T08:37:36.533 回答