背景
前兩天在做一個(gè)PC網(wǎng)站的意見反饋,其中涉及到了圖片上傳功能,要求可以上傳多張圖片,并且支持圖片上傳預(yù)覽及圖片刪除,
圖片上傳這一塊以前沒怎么搞過,而且一般也很少會碰到這樣的需求,所以在做這個(gè)功能的時(shí)候,參考了很多網(wǎng)上的代碼 ,
現(xiàn)在就單獨(dú)寫一篇博客來記錄下實(shí)現(xiàn)的整個(gè)過程,以及在做的過程中遇到的一些坑。
先來看下實(shí)現(xiàn)的最后效果:

首先先創(chuàng)建好一個(gè)用于展示預(yù)覽圖片及上傳按鈕的div,content-img-list用于動態(tài)展示預(yù)覽圖片,file用于顯示上傳按鈕
<div class="content-img">
<ul class="content-img-list">
<!-- <li class="content-img-list-item"><img src="https://www.baidu.com/img/bd_logo1.png" alt=""><a class="delete-btn"><i class="ico-delete"></i></a></li> -->
</ul>
<div class="file">
<i class="ico-plus"></i>上傳圖片,支持jpg/png<input type="file" name="file" accept="image/*" id="upload" >
</div>
</div>
上傳按鈕美化
默認(rèn)input type=file的上傳按鈕非常的丑陋,實(shí)現(xiàn)自定義上傳按鈕樣式,這里主要通過設(shè)置input的透明度將它設(shè)置為opacity: 0;
圖片上傳實(shí)現(xiàn)步驟
圖片上傳
通過jquery監(jiān)聽input change事件,這樣我們可以獲取到上傳的圖片流信息,從而可以獲取到圖片的地址、大小、格式以及名稱等信息
這里創(chuàng)建3個(gè)數(shù)組,imgName、imgSrc、imgFile分別用于存放上傳圖片的名稱、url地址以及圖片流信息
var fileList = this.files;
for(var i = 0; i < fileList.length; i++) {
var imgSrcI = getObjectURL(fileList[i]);
imgName.push(fileList[i].name);
imgSrc.push(imgSrcI);
imgFile.push(fileList[i]);
}
getObjectURL方法是一個(gè)用于獲取本地圖片的地址,使用該url可以顯示圖片
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 ;
}
控制上傳圖片大小、格式以及上傳數(shù)量
$('#upload').on('change',function(){
if(imgSrc.length==4){
return alert("最多只能上傳4張圖片");
}
var imgSize = this.files[0].size; //b
if(imgSize>1024*1024*1){//1M
return alert("上傳圖片不能超過1M");
}
if(this.files[0].type != 'image/png' && this.files[0].type != 'image/jpeg' && this.files[0].type != 'image/gif'){
return alert("圖片上傳格式不正確");
}
})
圖片預(yù)覽
創(chuàng)建一個(gè)addNewContent方法用于動態(tài)展示添加的圖片實(shí)現(xiàn)圖片預(yù)覽,在每次上傳圖片的時(shí)候調(diào)用該方法
function addNewContent(obj) {
$(obj).html("");
for(var a = 0; a < imgSrc.length; a++) {
var oldBox = $(obj).html();
$(obj).html(oldBox + '<li class="content-img-list-item"><img src="'+imgSrc[a]+'" alt=""><a index="'+a+'" class="hide delete-btn"><i class="ico-delete"></i></a></li>');
}
}
圖片刪除
1.通過監(jiān)聽鼠標(biāo)的mouseover事件,顯示圖片刪除按鈕
$('.content-img-list').on('mouseover','.content-img-list-item',function(){
$(this).children('a').removeClass('hide');
});
2.監(jiān)聽鼠標(biāo)的mouseleave事件,隱藏圖片刪除按鈕
$('.content-img-list').on('mouseleave','.content-img-list-item',function(){
$(this).children('a').addClass('hide');
});
3.獲取圖片index下標(biāo)屬性,通過js的splice方法刪除數(shù)組元素,重新調(diào)用addNewContent方法遍歷圖片數(shù)組顯示預(yù)覽圖片
$(".content-img-list").on("click",'.content-img-list-item a',function(){
var index = $(this).attr("index");
imgSrc.splice(index, 1);
imgFile.splice(index, 1);
imgName.splice(index, 1);
var boxId = ".content-img-list";
addNewContent(boxId);
if(imgSrc.length<4){//顯示上傳按鈕
$('.content-img .file').show();
}
});
圖片上傳提交
這里主要使用FormData來拼裝好數(shù)據(jù)參數(shù),提交到后臺
var formFile = new FormData();
遍歷imgFile圖片流數(shù)組拼裝到FormData中
$.each(imgFile, function(i, file){
formFile.append('myFile[]', file);
});
添加其他參數(shù)
formFile.append("type", type);
formFile.append("content", content);
formFile.append("mobile", mobile);
最后使用ajax提交內(nèi)容
$.ajax({
url: 'http://zhangykwww./webapi/feedback',
type: 'POST',
data: formFile,
async: true,
cache: false,
contentType: false,
processData: false,
// traditional:true,
dataType:'json',
success: function(res) {
console.log(res);
}
})
以上就實(shí)現(xiàn)了圖片上傳、圖片預(yù)覽和圖片刪除的功能
實(shí)現(xiàn)過程中遇到的坑
1.解決input file上傳圖片無法上傳相同的圖片 如果是相同圖片onChange事件只會觸發(fā)一次
onChange里面清除元素的value
document.querySelector('#uploader-get-file').value = null
也可以這樣this.value = null;
$('#upload').on('change',function(){//圖片上傳
this.value = null;//解決無法上傳相同圖片的問題
})
2.使用formData上傳file數(shù)組 3種方式(參考https://segmentfault.com/q/1010000009622562)
方式1:
$.each(getImgFiles(), function(i, file){
formData.append('files', file);
});
方式2:
$.each(getImgFiles(), function(i, file){
formData.append('files[]', file);
});
方式3:
$.each(getImgFiles(), function(i, file){
formData.append('files_' + i, file);
});
3.jquery設(shè)置 ajax屬性
processData : false, // 告訴jQuery不要去處理發(fā)送的數(shù)據(jù)
contentType : false,// 告訴jQuery不要去設(shè)置Content-Type請求頭
|