简体   繁体   English

模拟文件拖放并在dropzone.js中上传

[英]Simulated file drop and upload in dropzone.js

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. 我正在为包含dropzone.js元素的网页编写测试工具,我们将其myDropzone ,由$('#my-dropzone')元素表示。

Question: 题:

Can I use javascript to simulate dropping an uploadable file onto the dropzone? 我可以使用javascript模拟将可上传文件拖放到dropzone吗?

I think (but I'm not sure) this might entail something like: 我认为(但不确定),这可能需要执行以下操作:

  1. Creating a file-like object in javascript, then 在javascript中创建类似文件的对象,然后
  2. Triggering a drop event on myDropzone . 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. 步骤2很容易,但是步骤1涉及创建一个文件状对象(包含实际数据流?),一旦删除该对象就可以实际将其上传。

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. 我试图创建一个空文件,如这个 ,然后使用myDropzone.addFile(...)但因为没有数据有效载荷不会导致上载的文件。

thanks! 谢谢!

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. 我能够做的是从base64编码的文件(在本例中为图像)创建Blob文件,并将其传递给addFile(),因此它实际上是在模拟删除文件。

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

Where base64toBlob is: 其中base64toBlob是:

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/ 完整演示http://jsfiddle.net/P2dTF/52/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM