1. 程式人生 > >HTML5 手機端圖片上傳預覽

HTML5 手機端圖片上傳預覽

1、html頁面

<div class="addFile">
	<p class="company">資料上傳</p>
	<div class="photoes getoutinput">
		<div class="uplist">
	        <div class="fileList img" >
	            <img />
	         </div>
	         <button>上傳照片</button>
	          <input type="file" />
	      </div>
	      <p class="addMore">新增多張</p>
	</div>
</div>

2、css

.addFile{margin-top: 1rem;}
.getoutinput .uplist button,.bg-btn{background: #ff6600;color: #fff;}
.getoutinput .uplist{position: relative;}
.getoutinput .uplist input{position: absolute;left: 0;right: 0;bottom: 0;height: 4rem;width: 100%;opacity: 0;filter:Alpha(opacity=50)}
p.addMore{padding: 1rem 0;margin-top: 1rem;background: #ff6600;color: #fff;text-align: center;}

3、js

//點選更多新增增加圖片選擇顯示框
$(function(){
	$('.photoes').delegate('.addMore', 'click', function () {
		   $(this).prev().after('<div class="uplist">\n' +
		    <div class="fileList img"><img /></div>\n' +
		   <button>上傳照片</button><input type="file" name=""  />\n' +
		                ' </div><p class="addMore">新增多張</p>');
		    $(this).remove();
	 });
    //點選上傳照片,出發change事件
    $('.photoes').delegate('input', 'change', function (e) {        
		imgPreview(this);
        //adddata(this)
	});
					
});

第一種:這種方法是通過HTML5的FileReader解析,返回result可以用於圖片預覽

function imgPreview(fileDom){
	console.log(fileDom);
	//獲取檔案
    var file = fileDom.files[0];
    console.log(file);	
    //判斷是否支援FileReader
    if (window.FileReader) {
        var reader = new FileReader();
    } else {
        alert(裝置不支援");
       }      
    var imageType = /^image\//;
    //是否是圖片
    if (!imageType.test(file.type)) {
        alert("請選擇圖片!");
        return;
    }
    //讀取完成
    reader.onload = function(e) {
    	console.log(e);
        //獲取圖片dom
        var img = fileDom.parentNode.firstElementChild.firstElementChild;
        console.log(img)
        //圖片路徑設定為讀取的圖片
        var srcStr = e.target.result;
        img.src = srcStr;
        
    };
    reader.readAsDataURL(file);
}

 

 

第二種方法: 通過FormData提交,我這裡是選擇圖片後上傳到伺服器,伺服器返回給我一個圖片路徑,設定給圖片,所以我只提交了圖片file

function adddata(fileDom){
    var img = fileDom.parentNode.firstElementChild.firstElementChild;  
    var files = fileDom.files[0];
    console.log(files);
    var fd = new FormData();
    fd.append("files", files);
     
    console.log(fd);
    $.ajax({
        url: 'uploadFiles',
        type: 'POST',
        cache: false,
        data: fd,
        processData: false,// 告訴jQuery不要去處理髮送的資料
        contentType: false,// 告訴jQuery不要去設定Content-Type請求頭
        dataType: "json",
        success: function (data) {
           var src = data[0].fileurl;
           img.src = src;
        }
    });
}