3

I'm writing a test harness for a web page containing a dropzone.js element, let's call it myDropzone, represented by the $('#my-dropzone') element.

Question:

Can I use javascript to simulate dropping an uploadable file onto the dropzone?

I think (but I'm not sure) this might entail something like:

  1. Creating a file-like object in javascript, then
  2. Triggering a drop event on myDropzone.

Step #2 is easy, but step #1 involves creating a file-like object (containing real datastream?) that can actually be uploaded once it is dropped.

I've tried creating dummy files such as this and then using myDropzone.addFile(...), but that doesn't result in an uploadable file because there is no data payload.

thanks!

1 Answer 1

6

What I was able to do was create a Blob file from a base64 encoded file (image in this case) and pass that to addFile(), so it essentially is simulating dropping a file.

dropZone.addFile(base64toBlob(base64FileData, 'image/png'));

Where base64toBlob is:

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

    var byteCharacters = atob(b64Data);
    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);
    }

    var blob = new Blob(byteArrays, {type: contentType});
    return blob;
}

Full Demo http://jsfiddle.net/P2dTF/52/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.