input type=file實現圖片上傳,預覽以及圖片刪除


背景

前兩天在做一個PC網站的意見反饋,其中涉及到了圖片上傳功能,要求可以上傳多張圖片,並且支持圖片上傳預覽及圖片刪除,
圖片上傳這一塊以前沒怎么搞過,而且一般也很少會碰到這樣的需求,所以在做這個功能的時候,參考了很多網上的代碼 ,
現在就單獨寫一篇博客來記錄下實現的整個過程,以及在做的過程中遇到的一些坑。

先來看下實現的最后效果:

首先先創建好一個用於展示預覽圖片及上傳按鈕的div,content-img-list用於動態展示預覽圖片,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>

上傳按鈕美化

默認input type=file的上傳按鈕非常的丑陋,實現自定義上傳按鈕樣式,這里主要通過設置input的透明度將它設置為opacity: 0;

圖片上傳實現步驟

圖片上傳

通過jquery監聽input change事件,這樣我們可以獲取到上傳的圖片流信息,從而可以獲取到圖片的地址、大小、格式以及名稱等信息

這里創建3個數組,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方法是一個用於獲取本地圖片的地址,使用該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 ;
}

控制上傳圖片大小、格式以及上傳數量

	$('#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("圖片上傳格式不正確");
		}
	})

圖片預覽

創建一個addNewContent方法用於動態展示添加的圖片實現圖片預覽,在每次上傳圖片的時候調用該方法

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.通過監聽鼠標的mouseover事件,顯示圖片刪除按鈕

$('.content-img-list').on('mouseover','.content-img-list-item',function(){
		$(this).children('a').removeClass('hide');
	});

2.監聽鼠標的mouseleave事件,隱藏圖片刪除按鈕

$('.content-img-list').on('mouseleave','.content-img-list-item',function(){
		$(this).children('a').addClass('hide');
	});

3.獲取圖片index下標屬性,通過js的splice方法刪除數組元素,重新調用addNewContent方法遍歷圖片數組顯示預覽圖片

$(".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來拼裝好數據參數,提交到后台

var formFile = new FormData();

遍歷imgFile圖片流數組拼裝到FormData中

 $.each(imgFile, function(i, file){
            formFile.append('myFile[]', file);
        });

添加其他參數

    formFile.append("type", type); 
        formFile.append("content", content); 
        formFile.append("mobile", mobile); 

最后使用ajax提交內容

 $.ajax({
            url: 'http://zhangykwww.yind123.com/webapi/feedback',
            type: 'POST',
            data: formFile,
            async: true,  
            cache: false,  
            contentType: false, 
            processData: false, 
            // traditional:true,
            dataType:'json',
            success: function(res) {
                console.log(res);
            }
        })

以上就實現了圖片上傳、圖片預覽和圖片刪除的功能

實現過程中遇到的坑

1.解決input file上傳圖片無法上傳相同的圖片 如果是相同圖片onChange事件只會觸發一次
onChange里面清除元素的value

document.querySelector('#uploader-get-file').value = null

也可以這樣this.value = null;

$('#upload').on('change',function(){//圖片上傳
        this.value = null;//解決無法上傳相同圖片的問題
})

2.使用formData上傳file數組 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設置 ajax屬性

processData : false, // 告訴jQuery不要去處理發送的數據
contentType : false,// 告訴jQuery不要去設置Content-Type請求頭

戳我在線查看demo

完整的代碼我已經上傳到了https://github.com/fozero/frontcode,可以點擊查看,如果覺得還不錯的話,記得star一下哦!

相關鏈接
http://www.17sucai.com/pins/26463.html
https://blog.csdn.net/take_dream_as_horse/article/details/53197697
https://blog.csdn.net/qq_35556474/article/details/54575779
http://www.jb51.net/article/83894.htm
http://www.haorooms.com/post/css_input_uploadmh
https://www.cnblogs.com/LoveTX/p/7081515.html
http://www.haorooms.com/post/input_file_leixing

作者:fozero
聲明:原創文章,轉載請注明出處,謝謝!http://www.cnblogs.com/fozero/p/8835628.html
標簽:input,file,圖片上傳


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM