上传图片的功能是极为常用的,之前做过一个移动端上传文件的功能(基于jquery的),总结梳理一下。
html
<div class="uploadPic clearBox"> <ul> <li> <a href="javascript:void(0)" class="add001"><i class="iconfont"></i></a> <div class="moxie-shim moxie-shim-html5 upImgBox"> <a href="javascript:void(0)" class="del002 iconfont delImg" style="display:none"><span></span></a> <input id="fileUpload0" type="file" accept="image/png,image/gif,image/jpeg,image/bmp"> </div> </li> </ul> <div>
js
$('#fileUpload0').change(function() { uploadImg(this); }); function uploadImg(element){ var file = element.files[0]; var $elemt=$(element);
var $parent = $elemt.parent(); var imgFileSize = file.size; var loadingImgSrc='/images/global/loading.gif'; if(imgFileSize > 10*1024*1024) { alert(ci18n.imgTooLarge); } else { var uploadComplete=function(evt){ var resJson=JSON.parse(evt.target.responseText); if(resJson.fileurl){ $parent.find('img').attr('src',resJson.fileurl); uploadImgUrls['a'+$elemt.parent().parent().index()]=resJson.fileurl; $parent.find('.delImg').show(); $parent.parent('li').next().show(); } }; var uploadFailed=function(evt){ alert('Net error.'); }; var fd = new FormData(); fd.append('upfile',file); var xhr = new XMLHttpRequest(); xhr.addEventListener('load', uploadComplete, false); xhr.addEventListener('error', uploadFailed, false); xhr.open('POST', '/activity/group-upload'); $parent.append('<img src="'+loadingImgSrc+'">'); xhr.send(fd); } element.value = ''; } $('.delImg').click(function() { var $self=$(this);
var $parent = $self.parent(); delete uploadImgUrls['a'+$self.parent().parent().index()]; $parent.find('img').remove(''); $self.hide(); $parent.parent('li').next().hide(); });
效果:
点击“+”后会拉起选图片控件,选择之后会显示loading状态,上传成功之后,获取到图片地址之后,框内会显示上传的图片。
主要用了FromData来实现图片上传,并对于图片大小做了校验。