public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
String dir=servlet.getServletContext().getRealPath("/upload");
HtmlFileForm hff = (HtmlFileForm) form;
// org.apache.struts.upload.FormFile contains the uploaded file
FormFile file = hff.getFile();
// If no file was uploaded (e.g. first form load), then display View
if (file == null ) {
return mapping.findForward("success");
}
// Get the name and file size
String fname = file.getFileName();
String size = Integer.toString(file.getFileSize()) + " bytes";
InputStream streamIn = file.getInputStream();
OutputStream streamOut = new FileOutputStream(dir + "/"+fname);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.close();
streamIn.close();
// Populate the form bean with the results for display in the View
hff.setFname(fname);
hff.setSize(size);
// Clean up our toys when done playing
file.destroy();
// Forward to default display
return mapping.findForward("success");
}
------------------------------------------------------------------------------------
以上代码是孙卫琴的《精通struts:基于mvc的java web设计与开发》中关于文件上传的列子,偶的想法是,把上传的文件要根据当前系统时间进行重命名后在传到相应的upload目录。
例如:现在是2006年03月06日14:23:21,用户通过浏览指定某一个目录下的a.txt文件,当用户点上传按纽后,上传到服务器的upload目录下,就成了20060306142321.txt这个文件,请问在上边的方法中该怎么
实现,请路过的高人朋友说一下。谢谢。
A:
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
String dir=servlet.getServletContext().getRealPath("/upload");
HtmlFileForm hff = (HtmlFileForm) form;
// org.apache.struts.upload.FormFile contains the uploaded file
FormFile file = hff.getFile();
// If no file was uploaded (e.g. first form load), then display View
if (file == null ) {
return mapping.findForward("success");
}
// Get the name and file size
String fname = file.getFileName();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
java.util.Date mydate=new java.util.Date();
String s=sdf.format(mydate);
fname = s + fname .substring(fname.indexOf("."));
String size = Integer.toString(file.getFileSize()) + " bytes";
InputStream streamIn = file.getInputStream();
OutputStream streamOut = new FileOutputStream(dir + "/"+fname);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.close();
streamIn.close();
// Populate the form bean with the results for display in the View
hff.setFname(fname);
hff.setSize(size);
// Clean up our toys when done playing
file.destroy();
// Forward to default display
return mapping.findForward("success");
}