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");
}
已测试:单文件上传
最新推荐文章于 2026-06-23 20:24:54 发布
本文详细介绍了如何使用Struts框架进行文件上传操作,包括获取文件流、创建保存路径、生成文件名以及将文件写入服务器的过程,并处理上传过程中的异常。

2957

被折叠的 条评论
为什么被折叠?



