【发布时间】:2013-09-26 14:02:58
【问题描述】:
我比较了 VERSION1:标准 html 文件上传与 VERSION2:html5 fileApi 和 ajax 上传。事实证明,html5 fileApi 和 ajax 上传比旧的 html 文件上传慢很多。
- 为什么版本 2 的上传速度比版本 1 慢很多?
- 如何在 version2 中加快上传速度?
版本 1:
HTML
<g:form method="post" accept-charset="utf-8" enctype="multipart/form-data"
name="imageUploaderForm" id="imageUploaderForm" url="someurl">
<input type="file" accept="image/jpeg, image/gif, image/png"
name="image" id="image" />
</form>
JS(我用JQueryForm)
$("#image").change(function() {
$("#imageUploaderForm").ajaxForm({
complete: function(response){
console.log("upload complete");
}
});
$("#imageUploaderForm").submit();
});
服务器代码 Grails 2.2.4:
CommonsMultipartFile file = (CommonsMultipartFile) request.getFile('image')
byte [] imageBytes = file.getBytes()
版本 2:
HTML
<g:form method="post" accept-charset="utf-8" enctype="multipart/form-data"
name="imageUploaderForm" id="imageUploaderForm" url="someurl"></form>
<input id="UploadFileInput" class="UploadFileInput" type="file" name="image" accept="image/jpeg, image/gif, image/png" />
JS(我使用 filereader.js,它只是为 jquery 包装了 filereader api)我将上传的图像加载到 html5 画布中,因为我需要在上传之前操作图像。
var fileReaderOpts = {
readAsDefault: 'BinaryString',
on: {
load: function(event, file) {
var $img = $('<img>'),
imgWidth, imgHeight;
$img.load(function() {
// Create the canvas.
$originalCanvas = $('<canvas data-caman-hidpi-disabled>');
var originalContext = $originalCanvas[0].getContext('2d');
// Save image to canvas
$originalCanvas[0].width = this.width;
$originalCanvas[0].height = this.height;
originalContext.drawImage(this, 0, 0);
// some image modification on the canvas
// send image to server
var imageUrl = $originalCanvas[0].toDataURL();
$("#imageUploaderForm").ajaxForm({
data: {
img : imageUrl,
},
complete: function(response){
console.log("upload complete");
}
});
$("#imageUploaderForm").submit();
}); // end $img.load
// Set the src of the img, which will trigger the load event when done
$img.attr('src', event.target.result);
},// end load
beforestart: function(file) {
// Accept only images. Returning false will reject the file.
return /^image/.test(file.type);
}
}
};
// Bind the fileReader plugin the upload input and the drop area.
$("UploadFileInput").fileReaderJS(fileReaderOpts);
服务器代码 Grails 2.2.4:
String imgBase64 = params.image
imgBase64 = imgBase64.trim().replaceFirst("data:image/png;base64,", "")
byte[] imageBytes = Base64.decode(imgBase64.getBytes())
这是我测量的:
我已经上传了一个 7.5MB 大小的 jpg 图像,版本 1 和版本 2,以及 pinterest 和 flickr。在提交表单的那一刻,在客户端处理完图像后,我启动了 version1 和 version2 的计时器。
注意:画布相关的代码不包含在时间中。之后我开始测量。
结果:
- 版本 1:1.16 分钟
- 版本 2:3.43 分钟
- 兴趣:1.09 分钟
- flickr:1.11 分钟
【问题讨论】:
-
你怎么知道它比较慢?慢多少?包括有关您的指标的更多信息。什么比较慢(上传,或者包括画布相关代码的整个处理过程)?
-
@RayNicholus 我更新了我的问题中的结果。我在画布处理后开始测量。所以画布相关的代码就不包含在时间里了。
-
问题在于您的计算,或者您没有在此处显示所有代码。或者,还有其他一些环境问题,可能与带宽或服务器有关。
-
@RayNicholus 我使用相同的环境进行上传
-
我更新了我的服务器代码
标签: javascript html file-upload filereader