前台js
$("#imgUpload").change(function(e){
for(var i=0;i<e.target.files.length;i++){
var file = e.target.files.item(i);
if(!(/^image\/.*$/i.test(file.type)))
{
continue;
}
Goodsfiles.push(file)
}
ImgUpload(Goodsfiles,purl+'helpbuyUnfinished.dh?key=uploadImg");
})
function ImgUpload(files,url){
var formdata = new FormData();
if(files.length==0){
return ;
}
$.showPreloader($.i18n.prop('uploading'));
$.each(files, function(k, v){
formdata.append("fileList"+k, v);
});
$.ajax({
url : url,
type : 'POST',
data : formdata,
processData : false,
contentType : false,
dataType : 'json',
success : function(data) {
$.hidePreloader();
},
error : function(responseStr) {
}
});
}
后台接收
String uploadImg = "";
String url = request.getScheme()+"://";
url+=request.getHeader("host"); datefolder = DateUtility.getYear() + "/" + DateUtility.getMonth() + "/" + DateUtility.getDay()+"/";
String webParentPath = new File(request.getSession().getServletContext().getRealPath("/")).getParent();
String realPath = webParentPath + fileFolder;
System.out.println(realPath);
File file = new File(realPath);
if (!file.isDirectory()) {
file.mkdirs();
}
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("UTF-8");
List<?> fileList = upload.parseRequest(request);
Iterator<?> it = fileList.iterator();
while (it.hasNext()) {
Object obit = it.next();
if(obit instanceof DiskFileItem){
DiskFileItem item = (DiskFileItem) obit;
String fileName = UUID.randomUUID().toString().replace("-", "");;
BufferedInputStream imgin = new BufferedInputStream(item.getInputStream());
BufferedImage sourceImg =ImageIO.read(imgin);
//图片等宽 比例压缩 400px
int width = sourceImg.getWidth();
int height = sourceImg.getHeight();
BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(realPath+fileName)));
int h = (int) (height * 400 / width);
BufferedImage image = new BufferedImage(400, h,BufferedImage.TYPE_INT_RGB );
image.getGraphics().drawImage(sourceImg, 0, 0, 400, h, null);
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(outStream);
encoder.encode(image);
outStream.close();
imgin.close();
}
}