Search code examples
javascriptajaxbinary-datazendesk-apizendesk-app

Posting a base64 encoded PDF file with AJAX


I'm trying to post a base64-encoded PDF file to a Zendesk file upload API endpoint but the file URL returned from the API shows that the file is corrupted.

First I receive the PDF as a base64-encoded string from a separate API call. Let's call it base64String.

If I do window.open("data:application/pdf;base64," + base64String) I can view the PDF in my browser.

Now I am trying to follow the documentation here for uploading files via the API. I can successfully complete a cURL call as shown in the example. However, the jQuery AJAX call will corrupt the PDF file.

client.request({
  url: '/api/v2/uploads.json?filename=test.pdf',
  type: 'POST',
  data: atob(base64String),
  contentType: 'application/binary'
}).then(function(data) {
  window.open(data.upload.attachment.content_url);  // corrupt file
}, function(response) {
  console.log("Failed to upload file to Zendesk.");
  console.log(response);
});

Like I said, this will succeed but when I visit the content_url the PDF does not display. I am quite sure the file is being corrupt in the POST request.

I have tried uploading the file as a base64 string (without decoding with atob()) with no luck among other things.

UPDATE

I'm still not able to view the PDF after converting the base64 string to blob.

var blob = base64ToBlob(base64String);
console.log(blob);  // Blob {size:39574, type: "application/pdf"}

client.request({
  url: '/api/v2/uploads.json?filename=test.pdf',
  type: 'POST',
  data: blob,
  processData: false,
  contentType: 'application/pdf'
}).then(function(data) {
  window.open(data.upload.attachment.content_url);  // corrupt file
}, function(response) {
  console.log("Failed to upload file to Zendesk.");
  console.log(response);
});

function base64ToBlob(byteString) {
  // write the bytes of the string to an ArrayBuffer
  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  // write the ArrayBuffer to a blob, and you're done
  var blob = new Blob([ab], {type: 'application/pdf'});
  return blob;
};

Solution

  • I learned that the Zendesk app framework uses a jQuery AJAX wrapper for requests and the arraybuffer type is unsupported, so the file was getting corrupted. The app framework team has fixed the issue.