Jquery Ajax call fail with dataType 'binary' because responseType value is arraybuffer and not text

770 views Asked by At

I have to perform a jquery ajax call to download a file. The url refers to a controller method that returns a HttpResponseMessage, and there's not a single problem on this side (StatusCode 200, file bytes, everything seems fine).

Here is the ajax call

$.ajax({
  url: self.downloadAttachmentUrl,
  type: 'GET',
  cache: false,
  dataType: 'binary',
  data: {
    fileKey: fileKey,
    userId: userId
  },
  xhrFields: {
    responseType: 'arraybuffer'
  },
  beforeSend: function (xhr) {
    Object.keys(customAjaxHeaders).forEach(function (headerName) {
      var headerValue = customAjaxHeaders[headerName];
      xhr.setRequestHeader(headerName, headerValue);
    });
  },
  success: function (data, textStatus, jqXHR) {
    var fileName = self.getFileNameFromHeaders(jqXHR.getAllResponseHeaders());
    var blob = new Blob([data], { type: "application/octetstream" });
    self.downloadFile(blob, fileName)
  },
  error: function (jqXHR, textStatus, message) {
    console.error(textStatus, message);
  }
})*/

This call returns the following error

DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer').

I noticed that if I'm using "native ajax" (so no jQuery), I don't get this error, but I don't want to use it for a matter of consistency of the project (which is pretty dense).

var headers = new Headers();

Object.keys(customAjaxHeaders).forEach(function (headerName) {
  var headerValue = customAjaxHeaders[headerName];
  headers.append(headerName, headerValue)
});

var init = {
  method: 'GET',
  headers: headers
};

var fetchUrl = self.downloadAttachmentUrl + '?' + $.param({ fileKey: fileKey, userId: userId })

fetch(fetchUrl, init)
  .then(async response => {
    var blob = await response.blob();
    var fileName = self.getFileNameFromHeaders(response.headers.get('Content-Disposition'));
    var link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.setAttribute('download', fileName);
    link.click();
  })
});

Is there a way to make jQuery ajax call working without error ? Thanks for the help.

0

There are 0 answers