效果图:
样式:
.thumb {
height: 75px; /*给缩略图指定单个维度,浏览器自动等比缩放*/
border: 1px solid #000;
margin: 10px 5px 0 0;
}
html代码:
<div class="input">上传照片:
<input type="file" id="Files" name="imageFiles" accept="image/*" multiple />
<ul id="Errors"></ul>
<div style="color: #ccc; font-size: 10px;">如果需要查看原始尺寸图片,可点击相应图片;再次单击该图片,则恢复小图片。</div>
<div id="Preview"></div>
</div>
注意一定要在form上加上enctype="multipart/form-data"属性
js代码:
(function($) {
function fileSelect(e) {
$('#Preview').html('');
e = e || window.event;
var files = e.target.files; //FileList Objects
var ireg = /image\/.*/i,
p = document.getElementById('Preview');
var ul = document.getElementById('Errors');
for(var i = 0, f; f = files[i]; i++) {
if(!f.type.match(ireg)) {
var size = f.size;
if(size > 3072000){
alert("图片大小不能超过3M,请重新选择.");
return ;
}
//设置错误信息
var li = document.createElement('li');
li.innerHTML = '<li>' + f.name +'不是图片文件.</li>';
ul.appendChild(li);
continue;
}
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
var span = document.createElement('span');
span.innerHTML = '<img class="thumb" src="'+ this.result +'" alt="'+ file.name +'" />';
p.insertBefore(span, null);
};
})(f);
//读取文件内容
reader.readAsDataURL(f);
}
}
if(window.File && window.FileList && window.FileReader && window.Blob) {
document.getElementById('Files').addEventListener('change', fileSelect, false);
document.getElementById('Preview').addEventListener('click', function(e) {
if(e.target.tagName.toLowerCase() == 'img' && e.target.className == 'thumb') {
e.target.className = '';
} else if(e.target.tagName.toLowerCase() == 'img' && e.target.className == '') {
e.target.className = 'thumb';
}
});
} else {
document.write('您的浏览器不支持File Api');
}
})(jQuery);
后台代码:
@RequestMapping("saveVipQuestion")
public String auth(VipQuestion vipQuestion, Model model, HttpServletRequest request, HttpServletResponse response) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
List<MultipartFile> mFiles= multipartRequest.getFiles("imageFiles");
String imageUrl =FileUtils.uploadFile(mFiles,request,response);
}
//工具类上传方法
public static String uploadFile(List<MultipartFile> mFiles, HttpServletRequest request,
HttpServletResponse response) {
String imageUrl = "";
if (mFiles != null && !mFiles.isEmpty()) {
String realPath = SystemProperties.FILE_SHARE_ROOT;
//String realPath = "D:/sql/";//测试文件夹
StringBuffer imagesUrl = new StringBuffer();
for (int i = 0; i < mFiles.size(); i++) {
CommonsMultipartFile mFile = (CommonsMultipartFile) mFiles.get(i);
String fileName = mFile.getFileItem().getName();
Date now = new Date();
String original = "ggzj/question/" + DateUtil.formatDate(now, "yyyyMM") + "/" + fileName;
imagesUrl.append(original+",");
String outputPath = realPath + original;
try {
long fileLength = writeFile(mFile.getInputStream(), outputPath);
} catch (Exception e) {
logger.error("上传图片失败:{}", fileName, e);
}
}
imageUrl = imagesUrl.toString();
}
return imageUrl;
}