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;
        }
    });
}

猜你喜欢

转载自blog.csdn.net/LLL_liuhui/article/details/84136266