1.页面的form表单需要添加文件上传的标示: enctype="multipart/form-data"
基本原理:先读入,再写出
BufferedInputStream bis = null;BufferedOutputStream bos = null;
String imagePath;
long systemTime = System.currentTimeMillis();
picFileName = StringUtil.nullToString(systemTime)+picFileName;
try {
bis = new BufferedInputStream(new FileInputStream(pic));
BufferedInputStream imageBis = new BufferedInputStream(new FileInputStream(pic));
BufferedImage bi = ImageIO.read(imageBis);
int imageWidth = bi.getWidth();
int imageHeight = bi.getHeight();
if(imageWidth!=650 || imageHeight!=250 ){
resultMap.put("message", "需上传650*250尺寸的图片,请重新选择图片");
resultMap.put("success", "false");
return SUCCESS;
}
ServletContext application = ServletActionContext.getServletContext();
Map<String, Object> params = ActionContext.getContext().getParameters();
imagePath =params.get("savePath")+"/"+picFileName;
bos = new BufferedOutputStream(new FileOutputStream(application.getRealPath(savePath) + "/" + picFileName));
byte[] buf = new byte[1024];
int r = 0;
while((r = bis.read(buf)) != -1){
bos.write(buf,0,r);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
resultMap.put("message", "图片路径出错,请联系系统管理员!");
resultMap.put("error", true);
resultMap.put("success","false");
return SUCCESS;
} catch (IOException e) {
e.printStackTrace();
resultMap.put("message", "上传过程中出现问题,请重试!");
resultMap.put("error", true);
resultMap.put("success","false");
return SUCCESS;
}finally{
try {
if(bis != null){
bis.close();
}
if(bos != null){
bos.close();
}
} catch (IOException e){
e.printStackTrace();
}
}