2019独角兽企业重金招聘Python工程师标准>>>
ActionMessages msgs = new ActionMessages();
TestUploadForm upForm = (TestUploadForm)form;
String fileName = upForm.getPhoto().getFileName();//获取上传文件名称
int fileByteSize = upForm.getPhoto().getFileSize();//获取上传文件大小 -Byte
if(fileByteSize > BYTE_SIZE){//验证图片大小
msgs.add("photoSize", new ActionMessage("error.photo_size_empty"));
saveMessages(request, msgs);
return new ActionForward("/html/circle/album_add.vm?sid="+clForm.getSid(),false);
}
String fn = fileName.substring(fileName.lastIndexOf("."));
if( fn.equalsIgnoreCase(".jpg") || fn.equalsIgnoreCase(".gif")){//验证图片格式
Calendar calendar = new GregorianCalendar();
Date trialTime = new Date();
calendar.setTime(trialTime);
//使用当前时间创建保存图片的文件夹
String timePath = calendar.get(Calendar.YEAR)+"\\"+(calendar.get(Calendar.MONTH)+1)+"\\"+calendar.get(Calendar.DAY_OF_MONTH);
File uploadPath = new File(this.getServlet().getServletContext().getRealPath("uploads")+"\\photo\\"+timePath);
if(!uploadPath.exists())uploadPath.mkdirs();//如果文件夹不存在 创建文件夹
//设置存放图片的绝对地址
File upliadFile = new File(this.getServlet().getServletContext().getRealPath("uploads")+"\\circlePhoto\\"+timePath+"\\"+fileName);
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
bis = new BufferedInputStream(upForm.getPhoto().getInputStream());
Image img = javax.imageio.ImageIO.read(bis);
int photoWidth = img.getWidth(null);
int photoHeight = img.getHeight(null);
//图片规格 不符合规范...生成略缩图
if (photoWidth > WIDTH || photoHeight > HEIGHT) {
BufferedImage bi = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
bi.getGraphics().drawImage(img, 0, 0, WIDTH, HEIGHT, null);
bos = new BufferedOutputStream(new FileOutputStream(upliadFile));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(bi);
} else {//包存原有图片大小
BufferedImage bi = new BufferedImage(photoWidth, photoHeight,BufferedImage.TYPE_INT_RGB);
bi.getGraphics().drawImage(img, 0, 0, photoWidth, photoHeight, null);
bos = new BufferedOutputStream(new FileOutputStream(upliadFile));
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(bos);
encoder.encode(bi);
}
String path = (timePath+"\\"+fileName).replace("\\","/");
/**
* 最后向数据库中保存 图片地址
**/
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if (bis != null)bis.close();
if (bos != null)bos.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}else{
//格式不正确
msgs.add("photoType", new ActionMessage("error.photo_type_empty"));
saveMessages(request, msgs);
return new ActionForward("/html/circle/album_add.vm?sid="+clForm.getSid(),false);
}
第一次自己写上传操作.由很多不足的地方希望大家多多指教
原文链接: http://www.dlog.cn/nicholascoder/diary/8597