Fuzzyma
Fuzzyma

Reputation: 8474

Add blob to dropzone.js queue instead of file

I use dropzone.js to upload files. However my files are getting preprocessed before uploading. In the end I have a blob which I would like to upload. Unfortunately there is only a addFile() method available but no addBlob() method. I know I could use the File constructor like this:

new File([blob], 'filename', options)

but the constructor is not available in IE/Edge.

Is there any way to attach a blob to the dropzone.js queue?

Upvotes: 4

Views: 7223

Answers (1)

DarkKnight
DarkKnight

Reputation: 5944

addFile() can be used with blobs directly:

function dataURItoBlob(dataURI) {
  // http://stackoverflow.com/a/12300351/4578017
  var byteString = atob(dataURI.split(',')[1]);

  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

  var ab = new ArrayBuffer(byteString.length);
  var ia = new Uint8Array(ab);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }

  var blob = new Blob([ab], {type: mimeString});
  return blob;
}


$(() => {
  const options = {
    autoProcessQueue: false,
    url: "/file/post"
  };
  const myDropzone = new Dropzone( $('#dz').get(0), options);

  function addBlob(blob) {
    blob.name = 'myfilename.png'
    myDropzone.addFile(blob);
  }

  $('#preprocess').on('change', function() {
    const reader = new FileReader();
    reader.onload = () => {
      $('#data-uri').text(reader.result.slice(0, 64) + '...');
      addBlob(dataURItoBlob(reader.result));
    };
    reader.readAsDataURL(this.files[0]);
  });
})
#dz {
  height: 240px;
  width: 240px;
  background: #ccc;
}
<link href="https://github.com/enyo/dropzone/blob/master/dist/dropzone.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://raw.github.com/enyo/dropzone/master/dist/dropzone.js"></script>
<input id="preprocess" type="file">
<pre id="data-uri"></pre>
<div id="dz"> dropzone.js </div>

The File object is just a specific kind of a Blob, and addFile() doesn't require it to be a File.

Upvotes: 9

Related Questions