Struts2上传文件
实现步骤
1) 上传表单页面
<s:form action="/upload" method="POST" enctype="multipart/form-data">
<s:file label="选择文件:" name="file"/>
<s:submit value="上传"/>
</s:form>
2) 接收上传请求的Action
public class FileUploadAction extends ActionSupport { // 上传文件对象,该属性必须符合特定规范,即与表单提交name相同 private File file; // 上传文件的MIME类型 private String fileContentType; // 上传文件的文件名 private String fileFileName; // 上传至指定路径,该参数值由struts.xml配置 private String uploadPath; // 此处省略各Field的getter、setter方法 public String upload() throws Exception { OutputStream os = null; InputStream is = null; try { os = new FileOutputStream(uploadPath+fileFileName); is = new FileInputStream(file); byte[] buffer = new byte[1024]; int len = -1; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } } catch (Exception e) { e.printStackTrace(); }finally{ if(os!=null) os.close(); if(is!=null) is.close(); if(file!=null) is.close(); } return SUCCESS; } }
3) struts.xml配置文件
<package name="default" namespace="/" extends="struts-default"> <action name="upload" class="cn.itcast.user.action.FileUploadAction" method="upload"> <param name="filePath">d:/</param> <result name="input">/jsp/fial/upload_fail.jsp</result> <result>/jsp/success/upload_success.jsp</result> </action> </package>
struts2学习资料下载

浙公网安备 33010602011771号