一、文件上传
二、文件下载
三、传输文件大小问题
引用jar包为:
xwork-2.1.2.jar
struts2-core-2.1.6.jar
ognl-2.6.11.jar
jstl-1.2.jar
freemarker-2.3.13.jar
commons-logging-1.0.4.jar
commons-io-1.3.2.jar
commons-fileupload-1.2.1.jar
一、文件上传
上传我们从上传页面开始讲起,下面为上传页面upload.jsp。
其中,我们需要注意的是form标签中的enctype="multipart/form-data",没有这个不能上传文件。
- <%@ page language="java" contentType="text/html; charset=utf-8"%>
- <%@ taglib prefix="s" uri="/struts-tags"%>
- <html>
- <head>
- <title>upload</title>
- </head>
- <body>
- <script type="text/javascript">
- <!--addMore函数可以提供上传多个文件上传-->
- function addMore()
- {
- var td = document.getElementById("more");
- var br = document.createElement("br");
- var input = document.createElement("input");
- var button = document.createElement("input");
- input.type = "file";
- input.name = "upload";
- button.type = "button";
- button.value = " 删除 ";
- button.onclick = function()
- {
- td.removeChild(br);
- td.removeChild(input);
- td.removeChild(button);
- }
- td.appendChild(br);
- td.appendChild(input);
- td.appendChild(button);
- }
- </script>
- <!--<h3><font color="red">上传文件类型后缀为doc,ppt,xls,pdf,txt,java,每个文件大小不能大于50M</font></h3>-->
- <table align="center" width="50%">
- <tr>
- <td>
- <s:fielderror cssStyle="color:red" />
- </td>
- </tr>
- </table>
- <s:form action="upload.action" theme="simple" method="post"
- enctype="multipart/form-data">
- <table align="center" width="50%" border="1">
- <tr>
- <td>
- 上传文件
- </td>
- <td id="more" >
- <s:file name="upload"></s:file>
- <input type="button" value="上传更多..." onclick="addMore()">
- </td>
- </tr>
- <tr>
- <td>
- <s:submit value=" 确认 "></s:submit>
- </td>
- <td>
- <s:reset value=" 重置 "></s:reset>
- </td>
- </tr>
- </table>
- </s:form>
- </body>
- </html>
然后是struts.xml:
- <action name="upload" class="org.usc.file.UploadAction">
- <result name="input">/upload.jsp</result>
- <result name="success">/upload_success.jsp</result>
- </action>
跳转到UploadAction
文件上传路径为WebContent下的upload,所以最好先建立好此根目录
- package org.usc.file;
- import java.io.File;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.UUID;
- import org.apache.commons.io.FileUtils;
- import org.apache.struts2.ServletActionContext;
- import org.usc.utils.UploadConfigurationRead;
- import com.opensymphony.xwork2.ActionSupport;
- /**
- * 多文件上传类
- */
- public class UploadAction extends ActionSupport
- {
- /**
- *
- */
- private static final long serialVersionUID = 1L;
- private File[] upload;// 实际上传文件
- private String[] uploadContentType; // 文件的内容类型
- private String[] uploadFileName; // 上传文件名
- public String execute() throws Exception
- {
- try
- {
- //文件上传存放路径
- String targetDirectory = ServletActionContext.getServletContext()
- .getRealPath("/"+ UploadConfigurationRead.getInstance().getConfigItem("uploadFilePath").trim());// 获得路径
- for (int i = 0; i < upload.length; i++)
- {
- String fileName = uploadFileName[i];// 上传的文件名
- String type = uploadContentType[i];// 文件类型
- System.out.println("====filename:"+fileName);
- String realName = UUID.randomUUID().toString()+ getExt(fileName);// 保存的文件名称,使用UUID+后缀进行保存
- System.out.println("====getExt(fileName):"+getExt(fileName));
- System.out.println("====realName:"+realName);
- File target = new File(targetDirectory, realName);
- FileUtils.copyFile(upload[i], target);// 上传至服务器的目录,一般都这样操作,
- // 在把路径写入数据库即可
- System.out.println("====targetDirectory:"+targetDirectory);
- }
- } catch (Exception e)
- {
- e.printStackTrace();
- addActionError(e.getMessage());
- return INPUT;
- }
- return SUCCESS;
- }
- 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 static String getExt(String fileName)
- {
- return fileName.substring(fileName.lastIndexOf("."));
- }
- }
二、文件下载
struts.xml:
- <!-- 下载文件 -->
- <action name="download" class="com.DownloadAction">
- <result name="success" type="stream">
- <param name="contentDisposition">p_w_upload;filename="${fileName}"</param>
- <param name="inputName">downloadFile</param>
- </result>
- </action>
- <!-- 进入文件下载列表 -->
- <action name="inputdownload" class="com.DownloadAction" method="list">
- <result name="success">/download.jsp</result>
- </action>
下载文件实体类
- package com;
- /**
- * 文件类,需要的时候,可以和数据库进行关联
- */
- public class DownloadFiles
- {
- private String downloadFileName;//上传的文件名称
- private String downloadContentType;//类型
- private String downloadRealName;//保存的文件真实名称,UUID
- //如果使用数据库的话,建议这三个字段都进行保存
- public String getDownloadFileName() {
- return downloadFileName;
- }
- public void setDownloadFileName(String downloadFileName) {
- this.downloadFileName = downloadFileName;
- }
- public String getDownloadContentType() {
- return downloadContentType;
- }
- public void setDownloadContentType(String downloadContentType) {
- this.downloadContentType = downloadContentType;
- }
- public String getDownloadRealName() {
- return downloadRealName;
- }
- public void setDownloadRealName(String downloadRealName) {
- this.downloadRealName = downloadRealName;
- }
- }
文件下载的Action
- package com;
- import java.io.File;
- import java.io.InputStream;
- import java.io.UnsupportedEncodingException;
- import java.util.ArrayList;
- import java.util.List;
- import com.opensymphony.xwork2.ActionSupport;
- import org.apache.struts2.ServletActionContext;
- import com.UploadConfigurationRead;
- public class DownloadAction extends ActionSupport
- {
- private static final long serialVersionUID = 6329383258366253255L;
- private String fileName;
- private String fileRealName;
- private List<DownloadFiles> downloadFiles;
- //上传文件存放路径
- private final static String UPLOADDIR = "/upload";
- public List<DownloadFiles> getDownloadFiles() {
- return downloadFiles;
- }
- public void setDownloadFiles(List<DownloadFiles> downloadFiles) {
- this.downloadFiles = downloadFiles;
- }
- 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()方法才能在下载目录下正确找到请求的文件
- */
- if(null != fname && null != frealname){
- fname = new String(fname.getBytes("ISO-8859-1"), "UTF-8");
- frealname= new String(frealname.getBytes("ISO-8859-1"), "UTF-8");
- }else{
- fname = new String("null!");
- frealname= new String("null!");
- }
- } catch (Exception e)
- {
- e.printStackTrace();
- }
- this.fileName = fname;
- this.fileRealName = frealname;
- }
- /*
- * @getFileName 此方法对应的是struts.xml文件中的: <param
- * name="contentDisposition">p_w_upload;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;
- }
- public String list() throws Exception {
- //工程目录下的UPLOADDIR目录
- String dir = ServletActionContext.getServletContext().getRealPath(UPLOADDIR);
- System.out.println("====dir:"+dir);
- File file = new java.io.File(dir);
- File[] files = file.listFiles();
- System.out.println("====filenames:"+files.length);
- this.downloadFiles = new ArrayList<DownloadFiles>();
- for(int i=0;i<files.length;i++){
- DownloadFiles downloadFile = new DownloadFiles();
- downloadFile.setDownloadFileName(files[i].getName());
- downloadFile.setDownloadRealName(files[i].getAbsolutePath());
- downloadFile.setDownloadContentType("1");
- System.out.println("====Name:"+files[i].getName());
- System.out.println("====Absolutepath:"+files[i].getAbsolutePath());
- this.downloadFiles.add(downloadFile);
- }
- return SUCCESS;
- }
- }
文件下载页面download.jsp
- <%@ page language="java" contentType="text/html; charset=utf-8"%>
- <%@ taglib prefix="s" uri="/struts-tags"%>
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
- <html>
- <head>
- <title>download</title>
- </head>
- <body>
- <!-- 下面展示了两种显示下载文件列表的方式-->
- <%-- <s:iterator value="uploadFileName" id="downloadFileName">--%>
- <%-- <a href="download.action?name=<s:property value='%{#downloadFileName}'/>"><s:property value="%{#%{#downloadFileName}}" /> </a>--%>
- <%-- <br>--%>
- <%-- </s:iterator>--%>
- <table align="center" width="50%" border="1">
- <tr>
- <td align="center">
- 文件下载
- </td>
- </tr>
- <c:forEach var="downloadFiles" items="${downloadFiles}">
- <tr>
- <td>
- <!-- 因为我没有使用UUID来存储文件,所以此处 下载文件名与实际名相同-->
- <a
- href="download.action?name=${downloadFiles.downloadFileName }&realname=${downloadFiles.downloadFileName }">${downloadFiles.downloadFileName
- }</a>
- </td>
- </tr>
- </c:forEach>
- <s:debug/>
- </table>
- </body>
- </html>
三、传输文件大小问题
本文讲述的是在struts2框架下的文件上传与下载,struts2默认的文件最大值大约是2M,如果超过2M,文件将不上传,而添加拦截器的方式本人试过后也没有起效果。
以下是看到人家的一种解决方式:http://hi.baidu.com/%CE%D2%B0%AE%E1%B0%CF%D8/blog/item/92db3726f01f9926d4074287.html