【问题标题】:Wait for canvas.toBlob() before continue在继续之前等待 canvas.toBlob()
【发布时间】:2015-07-03 06:48:24
【问题描述】:

我想上传一张带有 jquery ajax 的裁剪图像。因此,我从 canvas 元素中创建了一个 blob 以将其附加到表单数据中。到目前为止这工作正常,但我猜我有一些同步/异步问题。我在网上搜索了 javascript 回调,但我不确定这是否是正确的。问题是

返回表单数据;

将在 blob 添加到表单数据之前执行。我认为有一个简单的解决方案可以解决我的问题,但我无法完成,也许你可以帮助我。

$.ajax({
    url: this.$upload.data('url'),
    method: 'POST',
    contentType: false,
    processData: false,
    cache: false,
    data: (function(_this) {
        var formData = new FormData();
        _this.getCroppedImage().toBlob(
            function(blob) {
                formData.append('file', blob, _this.file.name);
            },
            _this.file.type
       );
       $.each(_this.$element.data(), function(key, value) {
           formData.append(key, value);
       });
       return formData;
    })(this)
});

也许重要的是要知道:我还使用 https://github.com/blueimp/JavaScript-Canvas-to-Blob 让 toBlob 方法可用于所有浏览器。

【问题讨论】:

    标签: javascript jquery html canvas


    【解决方案1】:

    要实现这一点,您需要查看 Promise 对象,a good library for this is q.js

    基本上,您创建一个将构建表单数据的函数,然后等待表单数据完成,当 promise 解决时,它将通过“then”回调将表单数据传递给您的 ajax 函数。然后您的 ajax 调用将运行

    function ajaxFn(){
        //result is your formData in this case
        getFormData().then(function(result){
            //this won't run until the promise resolves, aka formData is complete
            $.ajax({
                url: this.$upload.data('url'),
                method: 'POST',
                contentType: false,
                processData: false,
                cache: false,
                data: result
            });
        });
    
    }
    
    function getFormData(){
        var deferred = Q.defer();
    
        var formData = new FormData();
    
        $.each(_this.$element.data(), function(key, value) {
           formData.append(key, value);
        });
    
        _this.getCroppedImage().toBlob(
            function(blob) {
                formData.append('file', blob, _this.file.name);
    
                //this is what will get passed into your then function above
                deferred.resolve(formData);
            },
            _this.file.type
       );
    
        return deferred.promise;
    }
    

    【讨论】:

    • 如果 jQuery 对你来说足够了,Q.defer() => jQuery.Deferred(); ................... deferred.promise => deferred.promise() ................................... ...................... ....... .then() 和 @987654326 @ 是兼容的 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 2019-01-20
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多