以下代码经过Firefox、Chrome浏览器测试没有问题,其余浏览器未作测试。
HTML代码:
<div id="billList"> </div> <div class="uploadBtn"> <div class="btn"> <p>点击上传</p> <p>票据凭证</p> </div> <input type="file" id="bill" multiple="multiple" accept=".jpg,.png,.jpeg,.gif" onchange="showPreview(this)"/> </div>
javascript代码:
function getObjectURL(file) {
var url = null;
if (window.createObjectURL != undefined) {//basic
url = window.createObjectURL(file);
} else if (window.URL != undefined) {//mozilla(firefox)兼容火狐
url = window.URL.createObjectURL(file);
} else if (window.webkitURL != undefined) {//webkit or chrome
url = window.webkitURL.createObjectURL(file);
}
return url;
}
function showPreview(source) {
var length = source.files.length;
var fileArr = [];
for(var i=0;i<length;i++){
fileArr.push(source.files[i]);
var objUrl = getObjectURL(source.files[i]);//调用函数调取图片地址
if (objUrl) {
var imgHtml = '<div class="bill"><img src="' + objUrl + '"></div>';
$('#billList').append(imgHtml);
}
}
}
$(function(){
$('.uploadBtn .btn').click(function(){
$(this).siblings('#bill').click();
});
});
根据实际应用情况修改。