//存放上传图片的服务器地址
List<String> imgList = null;
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 512);
ServletFileUpload fileUpload = new ServletFileUpload(factory);
fileUpload.setFileSizeMax(10 * 1024 * 1024);
String newName = null;
List<FileItem> items = fileUpload.parseRequest(request);
imgList = new ArrayList<String>();
for (FileItem item : items) {
if (!item.isFormField()) {
String image = null;
String name = item.getName();
String extName = name.substring(name.lastIndexOf("."));
newName = UUID.randomUUID().toString();
item.write(new File(request.getRealPath("/upload/" + newName + extName)));
image = "/upload/" + newName + extName;
imgList.add(image);
}
}
}
//jquery 实现上传图片并显示
function PreviewImage(imgFile, showId) {
var pattern = /(\.*.jpg$)|(\.*.png$)|(\.*.jpeg$)|(\.*.gif$)|(\.*.bmp$)/;
var show = $(showId);
var path;
if (!pattern.test(imgFile.value))
{
alert("仅支持jpg/jpeg/png/gif/bmp格式的照片!");
imgFile.focus();
}
else {
if (/msie/.test(navigator.userAgent.toLowerCase())) {
imgFile.select();
path = document.selection.createRange().text;
show.html = "";
show.css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='scale',src=\"" + path + "\")");
} else {
path = URL.createObjectURL(imgFile.files[0]);
show.html("<img src='" + path + "'/>");
}
}
}
<input type="file" name="front_image" class="upload" id="uoload_front" οnchange='PreviewImage(this, "#front_image")'/>