文件上传是常用的功能,upload.jsp是 我以前的选择,而现在则有更好的选择。配好struts2后只要以下几步:其实几步之间没有先后之分。
第一步:action里面的上传方法:
// ----------------上传 定义变量----------------------
private File NewFile; // 上传的文件
private String fileName; // 上传文件名
private String contentType; // 上传文件类型
private ServletContext context;
// ----------------文件上传----------------------
public String uploadFile() throws IOException {
context = ServletActionContext.getServletContext();
String targetDirectory = context.getRealPath("upload/cmsfile/");//文件服务器保存路径
fileName = renameFile(fileName);//重名
File target = new File(targetDirectory, fileName);
FileUtils.copyFile(NewFile, target);
return "upload";
}
// 文件重命名
private String renameFile(String fileName) {
DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
String formatDate = format.format(new Date());
int random = new Random().nextInt(10000);
int position = fileName.lastIndexOf(".");
String extension = fileName.substring(position);
return formatDate + random + extension;
}
// ----------------get set 方法----------------------
public void setNewFile(File newFile) {
NewFile = newFile;
}
public void setNewFileFileName(String fileName) {
this.fileName = fileName;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public void setServletContext(ServletContext context) {
this.context = context;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
第二步:上传页面。name属性action中要用到,这里个人认为用html标签比struts2的标签好
<s:form action="cms!uploadFile" method="post" theme="simple" οnsubmit="return checkForm()"
enctype="multipart/form-data">
<table>
<tr>
<td height="25">上传稿件</td>
<td><label>
<input name="NewFile" id="url" type="file" />
</label>
</td>
</tr>
</table>
</s:form>