3

我正在处理图像多上传,这听起来不错,但是..一如既往的内存问题。

脚本目标是在上传 100 多张图片 (300Mb+) 时存活下来。因此,如果您发现(我仍然是 javascript 蹩脚)任何问题,请给我一个建议。谢谢。

我的代码:

CFileReader.prototype.proccessFile = function(cb) {
    // this means File
    var reader = new FileReader();
    reader.readAsDataURL(this);
    reader.onload = (function (f) { 
        return function(e) {
            var image = new Image();
            image.src = e.target.result;
            image.onload = (function(f) {
                return function() {
                    var maxWidth = 700,
                        maxHeight = 700,
                        imageWidth = this.width,
                        imageHeight = this.height;

                    if (imageWidth > imageHeight) {
                      if (imageWidth > maxWidth) {
                        imageHeight *= maxWidth / imageWidth;
                        imageWidth = maxWidth;
                      }
                    }
                    else {
                      if (imageHeight > maxHeight) {
                        imageWidth *= maxHeight / imageHeight;
                        imageHeight = maxHeight;
                      }
                    }
                    var canvas = document.createElement('canvas');
                    canvas.width = imageWidth;
                    canvas.height = imageHeight;

                    var ctx = canvas.getContext("2d");
                    ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
                    if(typeof cb == 'function') {
                        cb(f,canvas.toDataURL());
                    }
                    delete canvas;
                    delete ctx;
                    return;
                }
            })(f);

        };
    })(this);    
}
4

2 回答 2

3

我认为 window.createObjectURL 比 FileReader 快,你应该同时使用这两种文件阅读器的后备......你也可以检查每个操作的性能,因为每个浏览器都有差异,例如http://jsperf.com/canvas-image-调整大小 并且不要忘记出于内存原因撤销ObjectURL ...您也可以使用网络工作者 http://www.html5rocks.com/en/tutorials/file/filesystem-sync/#toc-readingsync

    if("createObjectURL" in window || "URL" in window && 
    "createObjectURL" in window.URL || "webkitURL" in window && 
    "createObjectURL" in window.webkitURL) { 
        if("createObjectURL" in window) { 
            // Chrome exposes create/revokeObjectURL directly on window 
            objURL = window.createObjectURL(file); 
        } else if("webkitURL" in window) { 
            // Chrome exposes create/revokeObjectURL on the new  webkitURL API 
            objURL = window.webkitURL.createObjectURL(file); 
        } else { 
            // FF4 exposes create/revokeObjectURL on the new URL API 
            objURL = window.URL.createObjectURL(file); 
        } 

        // RESIZE image 
        // STORED IN    
        // objURL
} else { 
    // fallback to FileReader for FF3.6             
    reader = new FileReader();
    reader.onload =  function(event) {                                                                  
        // RESIZE image 
        // STORED IN    
        // event.target.result                 
    }

    reader.onprogress = function (evt) {
       if (evt.lengthComputable) {
            var percentLoaded = Math.round((evt.loaded / evt.total) * 100);
            console.log(percentLoaded);
       }
    }
    reader.readAsDataURL(file);                                                                 
} 
于 2013-04-30T18:12:37.357 回答
0

好吧,几天的谷歌搜索,几个小时的寻找最佳解决方案。(不是有史以来最好的,但最好的,我能想到的)。如果有人有更好的答案,或者只是给出坏名声。

目标一:将所有内容存储在全局空间中(画布、阅读器、画布上下文、图像)

window.reader = new FileReader();
window.canvas = document.createElement('canvas');
window.image = new Image();
window.ctx = window.canvas.getContext("2d");

目标二:使用 canvas.toBlob 方法(目前仅在 Firefox 中实现,您需要一些 polyfill)

目标三:增加一些等待,这我不能只是确定性地解释,它只是经验性的。目标是,允许浏览器在调用之间调用垃圾收集器。

所以这是我的最后一个开发脚本:

window.prepareFile = function (index,cb) {
    // this means file html element
    var res = window.configuration.photo.resolution.split(":");

    //var res = [300,200];
    var reader = window.reader;
    $('#fm-up-status > tr[for="'+this.files[index].name+'"]').children('td')[3].innerHTML = 'Zpracovávám';
    reader.readAsDataURL(this.files[index]);
    reader.onload = (function (f) { 
        return function(e) {
            setTimeout(function(){
                var image = window.image;
                image.src = e.target.result;
                image.onload = (function(f) {
                    return function() {
                        var maxWidth = parseInt(res[0]),
                            maxHeight = parseInt(res[1]),
                            imageWidth = this.width,
                            imageHeight = this.height;
                        if (imageWidth > imageHeight) {
                            if (imageWidth > maxWidth) {
                              imageHeight *= maxWidth / imageWidth;
                              imageWidth = maxWidth;
                            }
                        }
                        else {
                            if (imageHeight > maxHeight) {
                              imageWidth *= maxHeight / imageHeight;
                              imageHeight = maxHeight;
                            }
                        }
                        var canvas = window.canvas;
                        canvas.width =0;
                        canvas.width = imageWidth;
                        canvas.height = imageHeight;
                        window.ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
                        canvas.toBlob(
                            function (blob) {
                                var formData = new FormData();

                                formData.append('file', blob, f.name);
                                cb(f.name,formData);
                            },
                            'image/jpeg'
                        );
                        return;
                    }
                })(f);
                return;
            },500);
        };
    })(this.files[index]);

    return;
}

然后你可以简单地以普通形式(multipar)上传数据,如下所示:

window.uploader = function(filename,formdata,cb) {

    $('#fm-up-status > tr[for="'+filename+'"]').children('td')[3].innerHTML = 'Uploaduji';
    xhr = jQuery.ajaxSettings.xhr();
    if (xhr.upload) {
        xhr.upload.addEventListener('progress', function (evt) {
            if (evt.lengthComputable) {  
                var floatComplete = evt.loaded / evt.total;
                window.uploadProgress(filename,floatComplete);

            }
        }, false);
    }  
    provider = function () {
        return xhr;
    };    
    $.ajax({
        url: window.uploadUri,
        type: "POST",
        data: formdata,
        xhr: provider,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function (res,state,xhr) {
            cb(false,res,xhr);
            return;
        },
        error: function (xhr, state, err) {
            cb(err,false,xhr)
            return;
        }
    });    
};

这段代码实际上还没有准备好生产,它是一个简单的概念验证

于 2013-04-18T00:53:15.870 回答