1.首先在action中写如下代码
/* * fileupload,fileuploadFileName,fileuploadContentType命名规则,否则无法取值 * fileupload为客户端input上传组件的name,fileuploadFileName文件名称是fileupload+FileName组成,必须这样 * fileuploadContentType 文件类型是fileupload+ContentType组成,必须这样写 */ private File fileupload;//上传的文件 private String fileuploadFileName;//文件的名称 如上传的文件是a.png 则fileuploadFileName值为"a.png" private String fileuploadContentType;//文件的类型 如上传的是png格式的图片,则fileuploadContentType值为"image/png" /* * 指定上传文件在服务器上的保存目录,需要在Action中为定义savePath变量并为其添加相应的setter和getter方法 * 便于Struts2将struts.xml中的<param name="savePath">uploads/</param>值赋给savePath属性 */ private String savePath;//文件的保存位置 public String uploadFile() throws Exception { String absolutePath = ServletActionContext.getServletContext().getRealPath(""); // 获取项目根路径 //文件路径 String path = absolutePath + "/" + this.savePath + "/"; //创建路径,如果目录不存在,则创建 File file = new File(path); if(!file.exists()) { file.mkdirs(); } //文件路径+文件名 path +=this.getFileuploadFileName(); //1.构建输入流 FileInputStream fis = new FileInputStream(fileupload); //2.构建输出流 FileOutputStream fos = new FileOutputStream(path); //3.通过字节写入输出流 try { byte[] buf = new byte[1024]; int len = 0; while ((len = fis.read(buf)) > 0) { fos.write(buf, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { fis.close(); fos.close(); } return SUCCESS; } @JSON(serialize = false) public File getFileupload() { return fileupload; } public void setFileupload(File fileupload) { this.fileupload = fileupload; } @JSON(serialize = false) public String getSavePath() { return savePath; } public void setSavePath(String savePath) { this.savePath = savePath; } public String getFileuploadFileName() { return fileuploadFileName; } public void setFileuploadFileName(String fileuploadFileName) { this.fileuploadFileName = fileuploadFileName; } public String getFileuploadContentType() { return fileuploadContentType; } public void setFileuploadContentType(String fileuploadContentType) { this.fileuploadContentType = fileuploadContentType; }
2.在struts.xml中写入:
<action name="uploadFile" class="authResourcesAction" method="uploadFile"> <!-- 配置 fileupload 的拦截器 --> <interceptor-ref name="fileUpload"> <!-- 可以支持上传的文件类型 --> <param name="allowedTypes"> image/bmp,image/png,image/gif,image/jpeg,image/jpg </param> <!-- 设置上传文件的大小不能超过1M --> <param name="maximumSize">1024*1024</param> </interceptor-ref> <!-- 必须配置系统默认的拦截器 --> <interceptor-ref name="defaultStack" /> <!-- 设置上传文件的默认保存路径 --> <param name="savePath">uploads</param> <result name="input">/customer/addNew.jsp</result> <result name="success" type="redirect">/userMgr/userInfo.jsp</result> </action>
3.客户端jsp页面中:
<s:form action ="uploadFile" method ="POST" enctype ="multipart/form-data"> <s:file name ="fileupload"/> <s:submit value="上传" label="upload"/> </s:form>
*注意:form表单一定要是:method ="POST" enctype ="multipart/form-data"