2012-02-15 74 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

相关问题