2012-02-15 459 views
0

我正試圖從本地服務器下載文件。如果找不到該文件,則下載該文件的方法將顯示錯誤消息。是否可以從返回JsonResult的方法下載文件?

這是我認爲的代碼:

function download(id) { 
      var response = null; 
      var fileId = id == null? 0 : id; 
      var args = {fileId : fileId }; 

       $.ajax({ 
        type: 'POST', 
        url: '/Home/DownloadFile', 
        data: args, 
        dataType: "json", 
        traditional: true, 
        success: function (data) { 
         $("#message").attr('style', 'margin-left:auto; margin-right:auto; font-        weight: bold; color: Red'); 
         $("#message").html(data.message); 
        } 
       }); 
      } 
     } 

<div id="message"></div> 
<a class="fileName" href="javascript:void(0)" onclick='download(@f.Id)'>@f.Name</a> 

這是我的控制器:

public JsonResult DownloadFile(int fileId) 
    { 
     FileService fileService = new FileService(); 
     DirectoryService directoryService = new DirectoryService(); 
     File file = fileService.GetByFileId(fileId); 

     bool noError = false; 
     string _message = String.Empty; 

     if (file == null) 
     { 
      _message = "File does not exist"; 
     } 
     else if (System.IO.File.Exists(file.FilePath)) 
     { 
      using (StreamReader reader = System.IO.File.OpenText(file.FilePath)) 
      { 
       Stream s = reader.BaseStream; 
       byte[] fileData = Utils.ReadStream(s); 
       string contentType = Utils.getContentType(file.FileName); 

       Response.Clear(); 
       Response.Buffer = true; 
       Response.AddHeader("Content-Disposition", "attachment;filename=" + file.FileName); 
       Response.ContentType = contentType; 
       Response.BinaryWrite(fileData); 

       noError = true; 
      } 
     } 
     else 
     { 
      _message = "File \"" + file.FileName + "\" could not be found."; //File "foo.txt" could not be found 
     } 

     if (noError) 
      _message = String.Empty; 

     var data = new { message = _message }; 
     return Json(data, JsonRequestBehavior.AllowGet); 
    } 

奇怪的是,我測試了這是第一次,它的工作。我不記得改變任何東西,但現在該方法正常執行,但文件沒有下載。請有人幫助我嗎?

+0

您確定傳入的ID是正確的?文件被找到並且文件存在? – gideon 2012-02-15 03:40:43

+0

是的。我正在用調試器檢查所有這些。我的猜測是,阿賈克斯阻止我的文件被下載 – 2012-02-15 04:09:29

+0

這不是你應該使用的解決方案,但是如果你陷入困境並且沒有其他的解決方案,你可以試試這個:將文件下載方法移動到控制器/操作上(非ajaxed)。如果找到該文件,請將重定向發送到文件下載操作。不知道這是否會奏效,但我很確定這不是理想的答案。 – rkw 2012-02-15 06:25:42

回答

0

不,這是不可能的。您無法使用AJAX下載文件。你也不能有一個控制器動作返回兩個不同的東西:一個文件數據和JSON。不能使用AJAX下載文件的原因是因爲即使請求將被髮送到服務器,並且文件將到達AJAX success回調中的客戶端,您將獲得作爲參數傳遞的原始文件數據,但不存在你可以用它做很多事情。您無法將文件保存在客戶端計算機上,並且無法提示用戶選擇他想將文件存儲在他的計算機上的位置。

所以,如果你想下載文件使用正常的HTML鏈接或形式。沒有AJAX。

+0

謝謝。我也這麼想。你有什麼建議,我想要做什麼?基本上,我只是想讓用戶知道,如果文件沒有在服務器/ – 2012-02-17 03:30:47

相關問題