2015-06-08 91 views
3

下面是我的代碼:如何下載通過Ajax請求文件在asp.net MVC 4

ActionResult DownloadAttachment(student st) 
{   
    var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == st.Lisaid); 

    byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath); 
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);     
} 

這是我使用

$(function() { 
    $("#DownloadAttachment").click(function() { 
     $.ajax({ 
      url: '@Url.Action("DownloadAttachment", "PostDetail")', 
      contentType: 'application/json; charset=utf-8', 
      datatype: 'json', 
      type: "GET", 
      success: function() { 
       alert("sucess"); 
      } 
     });  
    }); 
});  

如何返回文件腳本尋求上述代碼下載?

回答

5

請試試這個在阿賈克斯成功

success: function() { 
    window.location = '@Url.Action("DownloadAttachment", "PostDetail")'; 
} 

更新答案:

public ActionResult DownloadAttachment(int studentId) 
{   
    // Find user by passed id 
    // Student student = db.Students.FirstOrDefault(s => s.Id == studentId); 

    var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == studentId); 

    byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath); 

    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);      

} 

Ajax請求:

$(function() { 
     $("#DownloadAttachment").click(function() { 
      $.ajax(
      { 
       url: '@Url.Action("DownloadAttachment", "PostDetail")', 
       contentType: 'application/json; charset=utf-8', 
       datatype: 'json', 
       data: { 
        studentId: 123 
       }, 
       type: "GET", 
       success: function() { 
        window.location = '@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })'; 
       } 
      }); 

     }); 
    }); 
+0

感謝那些工作,但如果我有這樣一個參數: 公衆的ActionResult DownloadAttachment(學生學生){ var文件=分貝.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == student.LisaId); }。在這種情況下,我必須將模型傳遞給downloadattachment,那麼我將如何追求?我已更新問題 –

+0

您是否更容易將模型ID傳遞給動作,然後通過ID找到您的學生,並根據學生模型數據做任何您想要的。我已經更新了答案。 –

+3

基本上,如果我們不給ajax調用仍然可以通過window.location下載文件,這只是因爲我們需要ajax請求,我們使用相同的成功函數感謝您的幫助。 –

0

下面的方法將有助於從jQuery的對話框Ajax請求調用行動窗口並且它執行動作並且可以在動作返回成功後立即關閉對話窗口SS導致

控制器

[HttpGet] 
    public ActionResult DownloadCampaign(string filePath, string mode) 
    { 
     string contentType = string.Empty; 
     var sDocument = filePath; 
     if (!System.IO.File.Exists(sDocument)) 
     { 
      return HttpNotFound(); 
     } 

     if (mode == "action") 
      return Json(new {fileName = filePath}, JsonRequestBehavior.AllowGet); 

     if (sDocument.Contains(".pdf")) 
     { 
      contentType = "application/pdf"; 
     } 
     else if (sDocument.Contains(".docx")) 
     { 
      contentType = "application/docx"; 
     } 
     else if (sDocument.Contains(".xls")) 
     { 
      contentType = "application/xlsx"; 
     } 

     return File(sDocument, contentType, sDocument); 
    } 

JQuery的 - Ajax請求

$(document) 
    .ready(function() { 
     $("#btnDownload").click(function() { 
      var file = $("#FilePath").val(); 
      $.ajax({ 
       url: '@Url.Action("DownloadCampaign", "FileList")', 
       data: { filePath: file, mode:'action' }, 
       method: 'GET', 
       dataType: 'json', 
       //contentType: 'application/json; charset=utf-8', 

       success: function(data) { 
        @*window.location = '@Url.RouteUrl("DownloadCampaign", "FileList", new { filePath = data1.fileName })';*@ 
        window.location.href = "@Url.RouteUrl(new 
        { Controller = "FileList", Action = "DownloadCampaign" })/?filePath=" + data.fileName + "&mode=download"; 
        $("#downloadFile_dialog").dialog("close"); 
       }, 
       error: function (req, status, errorObj) { 
        alert("Error"); 
       } 
      }); 

     }); 
}); 

請與我聯繫,如果您需要了解更多相關信息。

1

我認爲不需要Ajax調用,你可以簡單地使用超鏈接作爲下面的例子。

查看代碼

<a href="@Url.Action("DownloadAttachment", "PostDetail", new { studentId = 123 })">Download Form</a> 

控制器方法

public ActionResult DownloadAttachment(int studentId) 
{   
    // Find user by passed id 
    var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == studentId);  
    byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath);  
    return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename);       
}