最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

c# - How to display opensave dialog asp net mvc 4 - Stack Overflow

programmeradmin4浏览0评论

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

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();
}
Share Improve this question edited Jan 3, 2013 at 12:53 Cerbrus 72.9k19 gold badges136 silver badges150 bronze badges asked Jan 3, 2013 at 12:50 Guilherme LongoGuilherme Longo 2,3087 gold badges47 silver badges65 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 8

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 mvc you could have an action method to download a file resulting in a FileResult with the File method of the base controller.

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

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.

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");
}
发布评论

评论列表(0)

  1. 暂无评论