是否可以从返回JsonResult的方法下载文件?

时间:2012-02-15 03:30:16

标签: jquery ajax asp.net-mvc-3

我正在尝试从本地服务器下载文件。如果找不到该文件,则下载该文件的方法会显示错误消息。

这是我视图中的代码:

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

奇怪的是,我第一次测试这个,它起作用了。我不记得更改任何内容,但现在该方法正常执行,但文件未下载。拜托,有人可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

不,这是不可能的。您无法使用AJAX下载文件。此外,您不能拥有返回2个不同内容的控制器操作:文件数据和JSON。无法使用AJAX下载文件的原因是,即使请求将被发送到服务器并且文件将一直到达AJAX success回调中的客户端,您将获得原始文件数据传递为参数,但你用它做的并不多。您无法将文件保存在客户端计算机上,也无法提示用户选择要将文件存储在其计算机上的位置。

因此,如果您要下载文件,请使用普通的HTML链接或表单。没有AJAX。