1 回答

TA贡献1789条经验 获得超8个赞
可以用传参的方法
<img style="width:110px; height:110px;" id="picture_1" src="" alt="form1">
<input type="file" onchange="uploadPicturePre(this,'form1');">
<img style="width:110px; height:110px;" id="picture_2" src="" alt="form2">
<input type="file" onchange="uploadPicturePre(this,'form2');">
//定义数据关系
var picAll = {
form1: { id: '#picture_1', type: 'form1', blob: null },
form2: { id: '#picture_2', type: 'form2', blob: null },
form3: { id: '#picture_3', type: 'form3', blob: null },
form4: { id: '#picture_4', type: 'form4', blob: null }
};
//预览上传图片
//pictureType的值为form1、form2等
function uploadPicturePre(item, pictureType) {
$(picAll[pictureType].id).attr('src', '').hide();
picAll[pictureType].blob = null;
var me = item;
if (!me.files || !(new FileReader())) {
$(me).val('').get(0).parentNode.nextSibling.value = '';
alert('您的浏览器不支持files或FileReader对象');
return false;
}
if (me.files.length <= 0) {
$(me).val('').get(0).parentNode.nextSibling.value = '';
alert('您未选择文件');
return false;
}
var file = me.files[0];
if (!IsValidFileExtention(me.value, ["jpeg", "jpg", "png"])) {
$(me).val('').get(0).parentNode.nextSibling.value = '';
alert("文件格式不正确!");
return false;
}
var fileReader = new FileReader();
fileReader.onload = function () {
$(picAll[pictureType].id).attr('src', fileReader.result).show();
$(picAll[pictureType].id).attr('data-original', fileReader.result).show();
picAll[pictureType].blob = file;
};
fileReader.readAsDataURL(file);
}
思路大概是这样。。。
点击查看代码 运行及效果
截图如下:
添加回答
举报