1)提交表单设置
注意enctype一定要是"multipart/form-data"
2)Action代码
3)配置Action strutsl.xml
<form action="upload.do" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>选择文件</td>
<td>
<input type="file" name="upload" value=""/>
</td>
</tr>
<tr>
<td><input type="submit" value="上传文件" /></td>
</tr>
</table>
</form>
注意enctype一定要是"multipart/form-data"
2)Action代码
public class UploadAction extends ActionSupport {
private static final long serialVersionUID = 1224534552231961695L;
protected final Log logger = LogFactory.getLog(getClass());
private File upload; // 上传的临时文件
private String uploadContentType; // 文件的类型
private String uploadFileName; // 文件名
@Override
public String execute() throws Exception {
// 文件类型检查
if (! uploadContentType.equals("application/msword")) {
addFieldError("upload", "非法的上传文件类型");
return INPUT;
}
String tmpPath = ServletActionContext.getServletContext().getRealPath("tmp");
FileUtils.copyFile(upload, new File(tmpPath, uploadFileName)); // 拷贝文件
return SUCCESS;
}
// getter setter ...
}
3)配置Action strutsl.xml
<!-- ... -->
<action name="upload" class="net.csdn.struts.action.UploadAction">
<param name="allowedTypes">application/msword,text/html</param> <!-- 注入给Action用于配置允许上传类型 -->
<result name="success" type="dispatcher">/WEB-INF/jsp/success.jsp</result>
<result name="input" type="dispatcher">/index.jsp</result>
</action>