我有一个javascript应用程序,发送ajax POST请求到某个URL。Response可以是JSON字符串,也可以是文件(作为附件)。我可以很容易地在ajax调用中检测到Content-Type和Content-Disposition,但是一旦我检测到响应包含一个文件,我如何让客户端下载它呢?我在这里读过一些类似的帖子,但没有一个能提供我想要的答案。

请,请,请不要发布建议我不应该使用ajax或我应该重定向浏览器的答案,因为这些都不是一个选项。使用普通的HTML表单也是不可行的。我所需要的是向客户端显示一个下载对话框。这能做到吗?如何做到?


当前回答

如果response是一个数组缓冲区,在Ajax的onsuccess事件下尝试这个:

 if (event.data instanceof ArrayBuffer) {
          var binary = '';
          var bytes = new Uint8Array(event.data);
          for (var i = 0; i < bytes.byteLength; i++) {
              binary += String.fromCharCode(bytes[i])
          }
          $("#some_id").append("<li><img src=\"data:image/png;base64," + window.btoa(binary) + "\"/></span></li>");
          return;
      }

事件的地方。数据是XHR事件成功函数接收到的响应。

其他回答

我使用这个FileSaver.js。在我的情况下,与csv文件,我这样做(在coffescript):

  $.ajax
    url: "url-to-server"
    data: "data-to-send"
    success: (csvData)->
      blob = new Blob([csvData], { type: 'text/csv' })
      saveAs(blob, "filename.csv")

我认为对于大多数复杂的情况,必须对数据进行正确的处理。在底层,filesver .js实现了与Jonathan Amend的答案相同的方法。

我想指出在接受的答案中使用这种技术时出现的一些困难,即使用表单post:

You can't set headers on the request. If your authentication schema involves headers, a Json-Web-Token passed in the Authorization header, you'll have to find other way to send it, for example as a query parameter. You can't really tell when the request has finished. Well, you can use a cookie that gets set on response, as done by jquery.fileDownload, but it's FAR from perfect. It won't work for concurrent requests and it will break if a response never arrives. If the server responds with a error, the user will be redirected to the error page. You can only use the content types supported by a form. Which means you can't use JSON.

我最终使用在S3上保存文件并发送预签名URL来获取文件的方法。

对于那些从Angular角度寻找解决方案的人来说,这对我来说很管用:

$http.post(
  'url',
  {},
  {responseType: 'arraybuffer'}
).then(function (response) {
  var headers = response.headers();
  var blob = new Blob([response.data],{type:headers['content-type']});
  var link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = "Filename";
  link.click();
});

我使用了Naren Yellavula的解决方案,并在使用jquery尝试其他几个解决方案后,对脚本进行了很少的更改。但是,jquery将不能正确下载zip文件。下载后我无法解压缩文件。 在我的用例中,我必须上传一个压缩文件,该文件在Servlet中解压缩,在压缩文件下载到客户端之前,文件被处理并再次压缩。这是你在客户端需要做的事情。

$('#fileUpBtn').click(function (e){ e.preventDefault(); var file = $('#fileUpload')[0].files[0]; var formdata = new FormData(); formdata.append('file', file); // Use XMLHttpRequest instead of Jquery $ajax to download zip files xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState === 4 && xhttp.status === 200) { var a = document.createElement('a'); a.href = window.URL.createObjectURL(xhttp.response); a.download = "modified_" + file.name; a.style.display = 'none'; document.body.appendChild(a); a.click(); document.body.removeChild(a); window.URL.revokeObjectURL(a.href); } }; xhttp.open("POST", "<URL to Servlet>", true); xhttp.responseType = 'blob'; xhttp.send(formdata); }); <div class="form-group"> <label id="fileUpLabel" for="fileUpload"></label> <input type="file" class="form-control" id="fileUpload" name="file" accept="" required/> </div> <button class="btn" type="submit" id="fileUpBtn"></button>

下面是我下载多个文件的解决方案,取决于一些由一些id组成的列表,并在数据库中查找,文件将被确定并准备下载-如果存在的话。 我使用Ajax为每个文件调用c# MVC操作。

是的,就像其他人说的,它是可以在jQuery Ajax做到这一点。 我用Ajax成功做到了,我总是发送响应200。

所以,这是关键:

  success: function (data, textStatus, xhr) {

这是我的代码:

var i = 0;
var max = 0;
function DownloadMultipleFiles() {
            if ($(".dataTables_scrollBody>tr.selected").length > 0) {
                var list = [];
                showPreloader();
                $(".dataTables_scrollBody>tr.selected").each(function (e) {
                    var element = $(this);
                    var orderid = element.data("orderid");
                    var iscustom = element.data("iscustom");
                    var orderlineid = element.data("orderlineid");
                    var folderPath = "";
                    var fileName = "";

                    list.push({ orderId: orderid, isCustomOrderLine: iscustom, orderLineId: orderlineid, folderPath: folderPath, fileName: fileName });
                });
                i = 0;
                max = list.length;
                DownloadFile(list);
            }
        }

然后调用:

function DownloadFile(list) {
        $.ajax({
            url: '@Url.Action("OpenFile","OrderLines")',
            type: "post",
            data: list[i],
            xhrFields: {
                responseType: 'blob'
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader("RequestVerificationToken",
                    $('input:hidden[name="__RequestVerificationToken"]').val());

            },
            success: function (data, textStatus, xhr) {
                // check for a filename
                var filename = "";
                var disposition = xhr.getResponseHeader('Content-Disposition');
                if (disposition && disposition.indexOf('attachment') !== -1) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                    var a = document.createElement('a');
                    var url = window.URL.createObjectURL(data);
                    a.href = url;
                    a.download = filename;
                    document.body.append(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                }
                else {
                    getErrorToastMessage("Production file for order line " + list[i].orderLineId + " does not exist");
                }
                i = i + 1;
                if (i < max) {
                    DownloadFile(list);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {

            },
            complete: function () {
                if(i===max)
                hidePreloader();
            }
        });
    }

c# MVC:

 [HttpPost]
 [ValidateAntiForgeryToken]
public IActionResult OpenFile(OrderLineSimpleModel model)
        {
            byte[] file = null;

            try
            {
                if (model != null)
                {
                    //code for getting file from api - part is missing here as not important for this example
                    file = apiHandler.Get<byte[]>(downloadApiUrl, token);

                    var contentDispositionHeader = new System.Net.Mime.ContentDisposition
                    {
                        Inline = true,
                        FileName = fileName
                    };
                    //    Response.Headers.Add("Content-Disposition", contentDispositionHeader.ToString() + "; attachment");
                    Response.Headers.Add("Content-Type", "application/pdf");
                    Response.Headers.Add("Content-Disposition", "attachment; filename=" + fileName);
                    Response.Headers.Add("Content-Transfer-Encoding", "binary");
                    Response.Headers.Add("Content-Length", file.Length.ToString());

                }
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, "Error getting pdf", null);
                return Ok();
            }

            return File(file, System.Net.Mime.MediaTypeNames.Application.Pdf);
        }

只要你返回响应200,成功的Ajax可以与它一起工作,你可以检查文件是否实际存在,在这种情况下,下面的行将是假的,你可以通知用户:

 if (disposition && disposition.indexOf('attachment') !== -1) {