拖放文件上传

Drag n' Drop File Upload

我有一个网络应用程序,允许用户双击 DIV / 占位符,这反过来会打开浏览器上传对话框。选择图片后,我使用FileReader读取图片,并显示在指定的占位符中。

我想为此添加一个拖放组件。我研究过 Dropzone 和其他脚本,但它们似乎都做得太多了。我只需要能够将图像放在指定区域,并以某种方式连接到浏览器的基本文件上传,就好像图像是在传统意义上上传的一样。然后,我可以像往常一样将它传递给我的其余代码。

这是我当前代码的一个片段:

// This is within an updateImage() function which gets triggered by a user
// double-clicking a Div / image placeholder

    this.file = $('<input type="file" />');
    this.file.trigger('click');

    //keep a reference to this so that closures can use it
    var that = this;
    this.file.on('change', function(event) {
        var f = event.target.files[0];
        var reader = new FileReader();
        reader.onload = function(inner_event) {
            var image = new Image();
            image.onload = function() {
                // Get all the Image info
                that.user_image = inner_event.target.result;

然后在对数据进行一些处理和存储之后/CSS...

reader.readAsDataURL(f);

这是我想出的解决方案。本质上,我访问 dblclickdrop 事件:

// TheImageElement is a placeholder DIV

this.dom_element.on('drop', function(evt) {
    evt.stopPropagation();
    evt.preventDefault();
    that.updateImage(evt.originalEvent.dataTransfer.files[0]);
});


this.dom_element.on('dblclick', function() {
    that.handleImageUpload();
});

dblclick 事件调用 handleImageUpload() 触发文件 <input>:

this.ImageElement.prototype.handleImageUpload = function() {
    this.file = $('<input type="file" />');
    this.file.trigger('click');

    //keep a reference to this so that closures can use it
    var that = this;
    this.file.on('change', function(event) {
        that.updateImage(event.target.files[0]);
    });
}

现在,两种方法都调用 updateImage() 方法,并传递文件:

this.ImageElement.prototype.updateImage = function(theFile) {
    new_upload = true;
    // keep a reference to this so that closures can use it
    var that = this;
    var f = theFile;
    var reader = new FileReader();
    reader.onload = function(inner_event) {
        var image = new Image();
        image.onload = function() {

              // Some processing here
        }
     }
     reader.readAsDataURL(f);
}

所以现在,传统的双击和拖放都可以访问文件上传,使用相同的代码来处理它们。