Uploading file through Fetch


#1

I am trying to get an image from currently selected Artboard and upload it to a server. I am able to get base64 image but trying to convert it to a File so that it can be uploaded is not working.

Here is code for turning base64 to a blob. I never receive blob.

function b64toBlob(b64Data, contentType, sliceSize) {
  contentType = contentType || ''
  sliceSize = sliceSize || 512

  var byteCharacters = atob(b64Data)
  console.log(byteCharacters.length)
  var byteArrays = []

  for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
    var slice = byteCharacters.slice(offset, offset + sliceSize)

    var byteNumbers = new Array(slice.length)
    for (var i = 0; i < slice.length; i++) {
      byteNumbers[i] = slice.charCodeAt(i)
    }

    var byteArray = new Uint8Array(byteNumbers)

    byteArrays.push(byteArray)
  }
  console.log(byteArrays)
  console.log(contentType)
  var blob = await new Blob(byteArrays, { type: contentType })
  console.log(blob)
  return blob
}

#2

Console logging byteArrays and content type all works.

new Blob(byteArrays, { type: contentType }) seems to be the issue. And there are also no errors.


#3

Blobs aren’t currently supported by our fetch implementation. Instead, you’ll need to upload an ArrayBuffer. However that does mean changes on your backend to support the request.

Blob and FormData support are coming soon, though.


#4

How do I grab ArrayBuffer from the base64 image? Would it be the atob() function?


#5

So you’ve got an ArrayBuffer with byteArrays – you should be able to send that with fetch directly.