java struts2 上传包含jad等文件类型
简介:以前一直做上传些图片,txt,等类型的,上次需求变更,需要上传一个jad文件类型发现现有的不好用了,查找资料完善了struts2的上传
jar包
commons-fileupload-1.2.1.jar;
commons-io-1.4.jar;
commons-logging-1.0.4.jar;
freemarker-2.3.8.jar;
ognl-2.6.11.jar;
struts2-core-2.0.9.jar;
xwork-2.0.4.jar;
=======================UploadAction代码================================
//文件上传Action
//上传文件存放路径 webroot下面
private final static String UPLOADDIR = "/upload";
//上传文件集合
private List<File> file;
//上传文件名集合
private List<String> fileFileName;
//上传文件内容类型集合
private List<String> fileContentType;
public List<File> getFile() {
return file;
}
public void setFile(List<File> file) {
this.file = file;
}
public List<String> getFileFileName() {
return fileFileName;
}
public void setFileFileName(List<String> fileFileName) {
this.fileFileName = fileFileName;
}
public List<String> getFileContentType() {
return fileContentType;
}
public void setFileContentType(List<String> fileContentType) {
this.fileContentType = fileContentType;
}
public String execute() throws Exception {
//for (int i = 0; i < file.size(); i++) {
//循环上传每个文件
// uploadFile(i);
uploadFile(0);
//}
return "success";
}
//执行上传功能
private void uploadFile(int i) throws FileNotFoundException, IOException {
try {
InputStream in = new FileInputStream(file.get(i));
String dir = ServletActionContext.getRequest().getRealPath(UPLOADDIR);
File uploadFile = new File(dir, this.getFileFileName().get(i));
OutputStream out = new FileOutputStream(uploadFile);
byte[] buffer = new byte[1024 * 1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
=============upload.jsp===============
<s:form action="upload" method="post" enctype="multipart/form-data">
<tr>
<!-- 上传文件标签定义 -->
<td>上传文件:<s:file name="file"></s:file></td>
</tr>
<tr>
<td>再次上传文件:<s:file name="file"></s:file></td>
</tr>
<tr>
<td align="left"><s:submit name="submit" value="提交"></s:submit></td>
</tr>
</s:form>
=============result.jsp======
上传文件:
<!-- 显示上传成功文件名 -->
<s:property value="fileFileName" />