上傳圖片原型
㈠ 如何在前端用js進行多圖片上傳
產品提了一個需求,要求在一個html中實現多行多圖片上傳,原型圖如下:
2.1 :html
html頁面由前端實現,此處增加<ul><li></li></ul>是為了配合圖片單擊放大圖片功能的實現
<ul id="ul_other">
<li><input type="file" id="file_other" class="file_input" onchange="add_file_image('other')"></li>
</ul>
2.2 :js
var imgSrc_other=[];
var imgFile_other=[];
function add_file_image(id) {
var fileList =document.getElementById("file_"+id).files;// js 獲取文件對象
if (verificationFile(fileList[0])){
for(var i =0;i
var imgSrcI =getObjectURL(fileList[i]);
if (id=="other"){
imgSrc_other.push(imgSrcI);
if(fileList[i].size/1024 >100) { //大於100kb,進行壓縮上傳
fileResizetoFile(fileList[i],0.6,function(res){
imgFile_other.push(res);
})
}else{
imgFile_other.push(res);
}
}
addNewContent(id);
}
}
//新增圖片
function addNewContent(obj) {
//刪除原先
$("#ul_"+obj).html("");
//判斷循環新增
var text="";
if (obj=="other"){
for(var a =0;a < imgSrc_examReportCard.length;a++) {
text +='<li><input type="file" id="file_other" class="file_input" onchange="add_file_image('other')"></li>';
}
}else{
console.log('臟數據');
}
var oldBox ="<li><div class=\"filediv\"><span>+</span>\n" +
"<input type=\"file\" id=\"file_"+obj+"\" class=\"file_input\" onchange=\"add_file_image('"+obj+"')\">\n" +
"</div></li>";
$("#ul_"+obj).html( text+localText);
}
使用formData上傳
var form =document.getElementById("form_addArchive");//表單id
var formData =new FormData(form);
$.each(imgFile_other,function(i, file){
formData.append('imgFileOther', file);
});
$.ajax({
url:url,
type:'POST',
async:true,
cache:false,
contentType:false,
processData:false,
dataType:'json',
data:formData,
xhrFields:{
withCredentials:true
},
success:function(data) {
}
},
error:function(XMLHttpRequest, textStatus, errorThrown) {
}
})
後台使用@RequestParam(value ="imgFileOther", required=false) List<MultipartFile> imgFileOther, 接受
//獲取圖片url以便顯示
//文件格式驗證
//圖片壓縮