1 在Struts2中上传文件需要 commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar 这两个包。
2 确认页面form表单上的提交方式为POST,enctype属性的值为“multipart/form-data”。
fileupload.jsp页面:
<body>
<form action="<%=basePath%>lixiang/file_upload.action" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
FileUploadAction.java
package com.cy.action; import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException; import com.opensymphony.xwork2.ActionSupport; public class FileUploadAction extends ActionSupport{ private static final long serialVersionUID = 1L;
private File upload;
//获取上传文件类型
private String uploadContentType;
//获取上传文件名
private String uploadFileName;
//保存路径
private String savePath; public String upload(){ File dir = new File(savePath);
//先判断文件夹是否存在
if(!dir.exists()){
dir.mkdir();
} //再判断文件是否已经存在
String filePath = savePath + "\\"+uploadFileName;
File file = new File(filePath);//上传后的目标文件
FileOutputStream out = null;
FileInputStream in = null;
if(!file.exists()){
try {
out = new FileOutputStream(filePath);
in = new FileInputStream(upload); byte[] bytes = new byte[1024];
int lenth = 0;
while ((lenth = in.read(bytes)) > 0) {
out.write(bytes, 0, lenth);
} } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} return SUCCESS;
} // 提供set、get方法
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getSavePath() {
return savePath;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
} }
struts.xml
<action name="file_*" class="com.cy.action.FileUploadAction" method="{1}">
<param name="savePath">E:\images</param> <!-- 设置上传文件存放的路径 -->
<result name="success">/layout.jsp</result>
<result name="input">/fileupload.jsp</result>
</action>