Struts2下多文件的上传与下载(转)
struts.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 3 <!DOCTYPE struts PUBLIC 4 5 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 6 7 "http://struts.apache.org/dtds/struts-2.0.dtd"> 8 9 <struts> 10 <constant name="struts.i18n.encoding" value="utf8" /> 11 <package name="file" namespace="/" extends="struts-default"> 12 <action name="showUpload"> 13 <result>/upload.jsp</result> 14 </action> 15 <action name="upload" class="org.usc.file.UploadAction"> 16 <result name="input">/upload.jsp</result> 17 <!-- <result name="success">/upload_success.jsp</result>--> 18 <result name="success">/download.jsp</result> 19 <interceptor-ref name="fileUpload"> 20 <param name="maximumSize">2097152</param> 21 <param name="allowedTypes">image/bmp,image/x-png,image/png,image/gif,image/jpeg,image/jpg,image/pjpeg 22 </param>--> 23 </interceptor-ref> 24 <interceptor-ref name="defaultStack"></interceptor-ref> 25 </action> 26 27 <action name="download" class="org.usc.file.DownloadAction"> 28 <result name="success" type="stream"> 29 <param name="contentDisposition">attachment;filename="${fileName}" 30 </param> 31 <param name="inputName">downloadFile</param> 32 </result> 33 </action> 34 </package> 35 </struts>
就是文件上传和下载的一些Struts2配置,注意上传的时候,请引入
<interceptor-ref name="defaultStack"></interceptor-ref>,
下载的配置中注意:<param name="inputName">downloadFile</param>
其他的配置解释网上很多,不懂的可以先google学习一下。
UploadAction
在此文件中请注意文件数组的使用,因为是多文件
1 package org.usc.file; 2 3 import java.io.File; 4 5 import java.util.ArrayList; 6 7 import java.util.List; 8 9 import java.util.UUID; 10 11 import org.apache.commons.io.FileUtils; 12 13 import org.apache.struts2.ServletActionContext; 14 15 import org.usc.utils.UploadConfigurationRead; 16 17 import com.opensymphony.xwork2.ActionSupport; 18 19 20 /** 21 22 * 多文件上传类 23 24 * 25 26 * @author MZ 27 28 * 29 30 * @Time 2009-11-24下午09:26:44 31 32 */ 33 34 public class UploadAction extends ActionSupport{ 35 36 /** 37 38 * 39 40 */ 41 42 private static final long serialVersionUID = 1L; 43 44 private File[] upload;// 实际上传文件 45 46 private String[] uploadContentType; // 文件的内容类型 47 48 private String[] uploadFileName; // 上传文件名 49 50 private List<UploadFiles> uploadFiles = new ArrayList<UploadFiles>(); 51 52 public String execute() throws Exception{ 53 try { 54 55 String targetDirectory = ServletActionContext.getServletContext() 56 .getRealPath("/"+ UploadConfigurationRead.getInstance().getConfigItem("uploadFilePath").trim());// 获得路径 57 58 for (int i = 0; i < upload.length; i++) { 59 String fileName = uploadFileName[i];// 上传的文件名 60 String type = uploadContentType[i];// 文件类型 61 String realName = UUID.randomUUID().toString()+ getExt(fileName);// 保存的文件名称,使用UUID+后缀进行保存 62 File target = new File(targetDirectory, realName); 63 FileUtils.copyFile(upload[i], target);// 上传至服务器的目录,一般都这样操作, // 在把路径写入数据库即可 64 UploadFiles uf = new UploadFiles();// 创建文件 65 66 uf.setUploadContentType(type); 67 68 uf.setUploadFileName(fileName); 69 70 uf.setUploadRealName(realName); 71 uploadFiles.add(uf);// 添加到需要下载文件的List集合中 72 } 73 74 ServletActionContext.getRequest().setAttribute("uploadFiles", 75 76 uploadFiles); 77 78 } catch (Exception e){ 79 80 e.printStackTrace(); 81 82 addActionError(e.getMessage()); 83 return INPUT; 84 85 } 86 return SUCCESS; 87 88 } 89 90 public File[] getUpload(){ 91 return upload; 92 } 93 94 public void setUpload(File[] upload) 95 96 { 97 98 this.upload = upload; 99 100 } 101 102 103 104 public String[] getUploadContentType() 105 106 { 107 108 return uploadContentType; 109 110 } 111 112 113 114 public void setUploadContentType(String[] uploadContentType) 115 116 { 117 118 this.uploadContentType = uploadContentType; 119 120 } 121 122 123 124 public String[] getUploadFileName() 125 126 { 127 128 return uploadFileName; 129 130 } 131 132 133 134 public void setUploadFileName(String[] uploadFileName) 135 136 { 137 138 this.uploadFileName = uploadFileName; 139 140 } 141 142 143 144 public static String getExt(String fileName) 145 146 { 147 148 return fileName.substring(fileName.lastIndexOf(".")); 149 150 } 151 152 153 154 }
DownloadAction
在此文件中要注意public InputStream getDownloadFile()的名称在Struts2配置文件配置,返回的是一个InputStream类型的对象。
package org.usc.file; import java.io.InputStream; import java.io.UnsupportedEncodingException; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.ServletActionContext; import org.usc.utils.UploadConfigurationRead; public class DownloadAction extends ActionSupport { private static final long serialVersionUID = 6329383258366253255L; private String fileName; private String fileRealName; public void setFileName() { // 得到请求下载的文件名 String fname = ServletActionContext.getRequest().getParameter("name"); String frealname = ServletActionContext.getRequest().getParameter("realname"); try { /* * 对fname参数进行UTF-8解码,注意:实际进行UTF-8解码时会使用本地编码,本机为GBK。 * 这里使用request.setCharacterEncoding解码无效. * 只有解码了getDownloadFile()方法才能在下载目录下正确找到请求的文件 */ fname = new String(fname.getBytes("ISO-8859-1"), "UTF-8"); frealname= new String(frealname.getBytes("ISO-8859-1"), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } this.fileName = fname; this.fileRealName = frealname; // System.out.println(fileName); // System.out.println(fileRealName); } /* * @getFileName 此方法对应的是struts.xml文件中的: <param * name="contentDisposition">attachment;filename="${fileName}"</param> * 这个属性设置的是下载工具下载文件时显示的文件名, 要想正确的显示中文文件名,我们需要对fileName再次编码 * 否则中文名文件将出现乱码,或无法下载的情况 */ public String getFileName() throws UnsupportedEncodingException { fileRealName = new String(fileRealName.getBytes(), "ISO-8859-1"); return fileRealName; } /* * @getDownloadFile 此方法对应的是struts.xml文件中的: <param * name="inputName">downloadFile</param> 返回下载文件的流,可以参看struts2的源码 */ public InputStream getDownloadFile() { this.setFileName(); return ServletActionContext.getServletContext().getResourceAsStream("/"+UploadConfigurationRead.getInstance().getConfigItem("uploadFilePath").trim()+"/" + fileName); } @Override public String execute() throws Exception { return SUCCESS; } }
UploadConfigurationRead
package org.usc.utils; import java.io.File; import java.io.FileInputStream; import java.net.URI; import java.net.URISyntaxException; import java.util.Properties; /** * 动态读取配置文件类 * * @author MZ * * @Time 2009-11-24下午08:25:22 */ public class UploadConfigurationRead { /** * 属性文件全名,需要的时候请重新配置PFILE */ private static String PFILE = "upload.properties"; /** * 配置文件路径 */ private URI uri = null; /** * 属性文件所对应的属性对象变量 */ private long m_lastModifiedTime = 0; /** * 对应于属性文件的文件对象变量 */ private File m_file = null; /** * 属性文件所对应的属性对象变量 */ private Properties m_props = null; /** * 唯一实例 */ private static UploadConfigurationRead m_instance = new UploadConfigurationRead(); /** * 私有构造函数 * * @throws URISyntaxException */ private UploadConfigurationRead() { try { m_lastModifiedTime = getFile().lastModified(); if (m_lastModifiedTime == 0) { System.err.println(PFILE + "file does not exist!"); } m_props = new Properties(); m_props.load(new FileInputStream(getFile())); } catch (URISyntaxException e) { System.err.println(PFILE+"文件路径不正确"); e.printStackTrace(); } catch (Exception e) { System.err.println(PFILE+"文件读取异常"); e.printStackTrace(); } } /** * 查找ClassPath路径获取文件 * * @return File对象 * @throws URISyntaxException */ private File getFile() throws URISyntaxException { URI fileUri = this.getClass().getClassLoader().getResource(PFILE).toURI(); m_file = new File(fileUri); return m_file; } /** * 静态工厂方法 * * @return 返回ConfigurationRead的单一实例 */ public synchronized static UploadConfigurationRead getInstance() { return m_instance; } /** * 读取一特定的属性项 */ public String getConfigItem(String name, String defaultVal) { long newTime = m_file.lastModified(); // 检查属性文件是否被修改 if (newTime == 0) { // 属性文件不存在 if (m_lastModifiedTime == 0) { System.err.println(PFILE + " file does not exist!"); } else { System.err.println(PFILE + " file was deleted!!"); } return defaultVal; } else if (newTime > m_lastModifiedTime) { m_props.clear(); try { m_props.load(new FileInputStream(getFile())); } catch (Exception e) { System.err.println("文件重新读取异常"); e.printStackTrace(); } } m_lastModifiedTime = newTime; String val = m_props.getProperty(name); if (val == null) { return defaultVal; } else { return val; } } /** * 读取一特定的属性项 * * @param name * 属性项的项名 * @return 属性项的值(如此项存在), 空(如此项不存在) */ public String getConfigItem(String name) { return getConfigItem(name, ""); } }