How to upload base64-encoded image from JavaScript?

Uploadcare Upload API doesn’t support base64 encoding but you can upload any blob object directly with uploadcare.fileFrom('object', file), where file is any JS file or blob object. If for whatever reason your image is encoded in base64, you need to convert it to a File or Blob object before passing to the fileFrom function.

function dataURLtoFile(dataurl, filename) {
  let arr = dataurl.split(','),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]),
      n = bstr.length,
      u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  return new File([u8arr], filename, {type:mime});

let b64data = ... // some base64 encoded image string
let fileToUpload = dataURLtoFile(b64data, 'image');
let upload = uploadcare.fileFrom('object', fileToUpload);

upload.done(fileInfo => {

Thank you. I’ve been using an image cropper in Angular called ngx-image-cropper which outputs Base64 and I had no idea how to get it into a format I could use to upload.

1 Like