首页 > 解决方案 > Dropzone.js 进度条未使用 s3.managedUpload 在发射时更新

问题描述

我找到了几个关于如何使用 dropzone.js 独立测试它们进行 AWS 上传的示例,现在我正在尝试将它们组合成我们网站的图像上传器的完整表单。

我发现的一个示例表明您可以从 S3.managedUpload 触发进度更新,如下所示:

file.s3upload.on('httpUploadProgress', function(progress) {
    if (progress.total) {
        var percent = ((progress.loaded * 100) / progress.total);
        console.log('httpUploadProgress', percent, progress.loaded);
        myDropzone.emit('uploadprogress', file, percent, progress.loaded);
    }
});

使用我的 console.log ,我可以看到 httpUploadProgress 的多个循环,百分比越来越高。但是 {dropzone}.emit 似乎没有更新进度条。

我已经尝试使用外部 'myDropzone' var 以及将我的 AWSSendFile 函数(包含上述代码)作为 dropzone 本身的原型,因此我可以使用 this.emit() 来引用它。没运气。

拖放区模板是:

dropzoneTemplate:'
<div class="Item dropzone-previews">
  <div class="Icon"><img data-dz-thumbnail /></div>
  <div class="Description dz-preview dz-file-preview">
    <span class="Filename" data-dz-name ></span><br/>
    <div class="dz-progress"><span class="dz-upload dz-progress" data-dz-uploadprogress ></span></div>
  </div>
</div>'

带有原型函数的完整代码:

// override the uploadFiles function to send via AWS SDK instead of xhr
Dropzone.prototype.uploadFiles = function (files) {
    for (var j = 0; j < files.length; j++) {
        var file = files[j];
        this.AWSsendFile(file);
    }
};
Dropzone.prototype.AWSsendFile = function(file) {
    let dz = this;
    file.s3upload.send(function(err, data) {
        if (err) {
            dz.emit("error", file, err.message);
        } else {
            dz.emit("complete", file);
        }
    });

    // listen to the AWS httpUploadProgress event, and emit an equivalent Dropzone event
    file.s3upload.on('httpUploadProgress', function(progress) {
        if (progress.total) {
            var percent = ((progress.loaded * 100) / progress.total);
            console.log('httpUploadProgress', percent, progress.loaded);
            dz.emit('uploadprogress', file, percent, progress.loaded);
        }
    });
};

function acceptCallback(file, done) {
    // options for the managed upload for this accepted file
    // define the bucket, and the S3 key the file will be stored as
    let fullKey = userId + "/" + file.name;
    let params = {
        Bucket: bucket,
        Key: fullKey,
        Body: file,
        Region: 'us-east-2'
    };
    // add an S3 managed upload instance to the file
    file.s3upload = new AWS.S3.ManagedUpload({params: params});
    done();
};
function abortUpload(file) {
    if (file.s3upload) file.s3upload.abort();
};

示例 console.log 数据:

   httpUploadProgress 97.33840304182509 49152 
   httpUploadProgress 100 50496

更新:我注意到异步嵌入式回调存在一个问题,并修改了上面的“原型”函数以显示我的更改。为 dz = this 设置一个局部变量来保存主 dropzone 对象的句柄。这使得进度条可以正常工作,现在达到 100%,但现在“完成”发出调用似乎并没有告诉它显示为完成。

标签: dropzone.jsaws-sdk-js

解决方案


推荐阅读