2013-01-03 17 views
5

Jestem w stanie zażądać pliku, a także go zwrócić. Nie wiem, jak wyświetlić okno dialogowe otwierania/zapisywania.Jak wyświetlić okno dialogowe otwierania/zapisywania asp net mvc 4

Widok:

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

Kontroler:

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

Odpowiedz

7

Myślę, że nie można pobrać plik w async przeglądarki, po prostu przekierować użytkownika do działania, a przeglądarka otworzy okno dialogowe zapisu. W asp.net mvc możesz mieć metodę działania, aby pobrać plik, w wyniku czego FileResult z metodą File kontrolera podstawowego.

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

Wielkie dzięki! –

+1

Jest pobierany automatycznie, bez pytania. Okno dialogowe się nie wyświetla! –

+3

To zależy od przeglądarki. Jeśli ustawisz pobieranie automatycznie do danego folderu, przeglądarka pobierze automatycznie. Firefox i Chrome to niektóre przeglądarki o takim działaniu. –

1

Jednym ze sposobów, aby zmusić Firefox (doen't pracy dla Chrome), aby otworzyć zapisać dialog jest ustawienie ContentType do „application/octet-stream” i nadać mu nazwę z poprawnym rozszerzeniem.

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"); 
} 
Powiązane problemy