文件上传功能的疑问???

ljs_002 ljs_002 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
/* 文件上传预览图 */
function FileLoad(settings) {
this.input = settings.input;
this.imgView = settings.imgView;
this.delBtn = settings.delBtn;
this.init();
}
var image_base64="";
var image_name="";
FileLoad.prototype = {
init: function () {
var _this = this;
//
if (typeof(FileReader) === 'undefined') {

} else {
//“change”方法绑定,触发文件读取方法
this.input.on("change", function () {
_this.readFile.call(_this);
});
}
//del方法清除绑定信息
_this.delBtn.on("click", function (e) {
_this.imgView.html("");
_this.input.val("");
image_name="";
image_base64="";
$(this).hide();
})
},
readFile: function () {
var _this = this;
var file = this.input[0].files[0];//获取文件
if(file.size>3145728){
//alertWarning('请上传小于3M的图片','top');
alert('请上传小于3M的图片');
$("#fileInput").val("");
return false;
}
image_name=file.name;
var fileType = file.type;
if (fileType && !/image\/\w+/.test(fileType)) {
alert("请上传图片文件");
return false;
}

var $img = new Image();
//问题一:“webkitURL.createObjectURL”是什么作用?
var url = webkitURL.createObjectURL(file);
$img.onload = function() {
//生成比例
var width = $img.width;
var height = $img.height;
if (width>height){
if (width>600){
height = height * (600/width);
width = parseInt(600);
}
}else if (height > width){
if (height > 600){
width = width * (600/height);
height = parseInt(600);
}
}else {
if (width >600){
width = parseInt(600);
height = parseInt(600);
}
}
//生成canvas
var $canvas = document.createElement('canvas');
var ctx = $canvas.getContext('2d');
$canvas.width= width;
$canvas.height = height;
ctx.drawImage($img, 0, 0, width, height);
问题二:为什么要先将图片放入canvas中,然后再从canvas中获取图片?
image_base64 = $canvas.toDataURL('image/png',0.3);
image_base64=encodeURIComponent(image_base64);
问题三:“encodeURIComponent”作用是什么???
_this.imgView.html('<img src="'+url+'"/>');
_this.delBtn.show();
}
$img.src = url;
}
}
...全文

相关推荐

评论 2
收藏 已收藏
分享
返回顶部
ljs_002
JavaScript 87,984 成员 224,681 内容