public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
com.cn.struts.form.UploadForm uploadform =(UploadForm)form;
String context = this.servlet.getServletContext().getRealPath("/");
System.out.println("context: "+context);
org.apache.struts.upload.FormFile formfile = uploadform.getFile();
java.io.InputStream is = null;
java.io.OutputStream os = null;
try {
is = formfile.getInputStream();
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);
System.out.println("timePath: "+timePath);
//如果文件夹不存在,则建立
String dir=this.getServlet().getServletContext().getRealPath("userUploadPhoto")+"//photo//"+timePath;
File uploadPath = new File(dir);
if(!uploadPath.exists())
uploadPath.mkdirs();
//生成上传的文件名
String ext=formfile.getFileName().split("//.")[1];
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date d=new Date();
sdf.applyPattern("HHmmssSSS");
String filename=sdf.format(d) +(Math.random()+"").substring(2,7);
filename =filename+ "." + ext;
System.out.println("filename===" + filename);
os = new FileOutputStream(dir+"//" + filename);
byte[] bytes = new byte[8192];
while ((is.read(bytes, 0, 8192)) != -1) {
os.write(bytes, 0, 8192);
}
if (os != null)
os.close();
if (is != null)
is.close();
request.setAttribute("msg", "上传成功");
} catch (FileNotFoundException e) {
e.printStackTrace();
request.setAttribute("msg", "上传失败");
} catch (IOException e) {
e.printStackTrace();
request.setAttribute("msg", "上传失败");
}
return mapping.findForward("msg");
}