Struts2 框架实现多文件上传下载
2013-01-11 14:57
597 查看
web.xml配置:
[xhtml] view plaincopyprint?<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
</web-app>
struts.xml配置:
[xhtml] view plaincopyprint?<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constantname="struts.i18n.encoding"value="utf-8"/>
<packagename="file"extends="struts-default">
<actionname="showUpload">
<result>/upload.jsp</result>
</action>
<actionname="upload"class="com.boxun.hzw.action.UploadAction">
<resultname="input">/upload.jsp</result>
<result>/download.jsp</result>
<interceptor-refname="fileUpload">
<paramname="maximumSize">2097152</param>
<paramname="addowedTypes">image/bmp,image/jpg</param>
</interceptor-ref>
<interceptor-refname="defaultStack"></interceptor-ref>
</action>
<actionname="download"class="com.boxun.hzw.action.DownloadAction">
<resultname="success"type="stream">
<paramname="contentDisposition">attachment;filename="${fileName}"</param>
<paramname="inputName">downloadFile</param>
</result>
</action>
</package>
</struts>
后台实体类代码:
[java] view plaincopyprint?package com.boxun.hzw.bean;
publicclass UploadFiles {
private String uploadContentType;
private String uploadFileName;
private String uploadRealName;
public String getUploadContentType() {
return uploadContentType;
}
publicvoid setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getUploadFileName() {
return uploadFileName;
}
publicvoid setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getUploadRealName() {
return uploadRealName;
}
publicvoid setUploadRealName(String uploadRealName) {
this.uploadRealName = uploadRealName;
}
}
上传Action类:
[java] view plaincopyprint?package com.boxun.hzw.action;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.boxun.hzw.bean.UploadFiles;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("all")
publicclass UploadAction extends ActionSupport {
privatestaticfinallong serialVersionUID = 1L;
private File[] upload; //实际上传文件
private String[] uploadContentType; //文件的内容类型
private String[] uploadFileName; //上传文件名
private List<UploadFiles> uploadFiles = new ArrayList<UploadFiles>();
public String execute(){
String targetDirectory = ServletActionContext.getServletContext().getRealPath("/"+"images/");//获得路径
for(int i = 0 ; i < upload.length ; i++){
String fileName = uploadFileName[i]; //上传的文件名
String type = uploadContentType[i]; //文件类型
String realName = UUID.randomUUID().toString() +
getExt(fileName); //保存的文件名称、使用UUID+后缀进行保存
File target = new File(targetDirectory,realName);
try {
FileUtils.copyFile(upload[i],target);//上传至服务器的目录
} catch (IOException e) {
e.printStackTrace();
return INPUT;
}
//把路径()写入数据库 ---省略---
UploadFiles uf = new UploadFiles(); //创建文件
uf.setUploadContentType(type);
uf.setUploadFileName(fileName);
uf.setUploadRealName(realName);
uploadFiles.add(uf); //添加到需要下载文件的List集合中
}
ServletActionContext.getRequest().setAttribute("uploadFiles", uploadFiles);
return SUCCESS;
}
public File[] getUpload() {
return upload;
}
publicvoid setUpload(File[] upload) {
this.upload = upload;
}
public String[] getUploadContentType() {
return uploadContentType;
}
publicvoid setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String[] getUploadFileName() {
return uploadFileName;
}
publicvoid setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}
public List<UploadFiles> getUploadFiles() {
return uploadFiles;
}
publicvoid setUploadFiles(List<UploadFiles> uploadFiles) {
this.uploadFiles = uploadFiles;
}
publicstaticlong getSerialversionuid() {
return serialVersionUID;
}
publicstatic String getExt(String fileName){
return fileName.substring(fileName.lastIndexOf("."));
}
}
下载Action类:
[java] view plaincopyprint?package com.boxun.hzw.action;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("all")
publicclass DownloadAction extends ActionSupport {
privatestaticfinallong serialVersionUID = 6329383258366253255L;
private String fileName;
private String fileRealName;
publicvoid setFileName(){
//得到请求下载的文件名
String fname = ServletActionContext.getRequest().getParameter("name");
String frealname = ServletActionContext.getRequest().getParameter("realname");
try {
/*
* 对fname参数进行utf-8解码、注意:实际进行utf-8解码时会使用本地编码、本机为GBK。
* 这里使用reqeust.setCharacterEncoding解码无效.
* 只有解码了getDownloadFile()方法才能在下载目录下正确找到请求的文件
*/
fname = new String(fname.getBytes("ISO-8859-1"),"utf-8");
frealname = new String(frealname.getBytes("ISO-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
this.fileName = fname;
this.fileRealName = frealname;
}
/*
* @getFileName 此方法对应的是struts.xml文件中的:
* <param name ="contentDisposition"> attachment;filename="${fileName}"</param>
* 这个属性设置的是下载工具下载文件时显示的文件名、要想正确的显示中文文件名,
* 我们需要对fileName再次编码
* 否则中文名文件将出现乱码、或无法下载情况
* @return
*/
public String getFileName(){
try {
fileRealName = new String (fileRealName.getBytes(),"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fileRealName;
}
/*
* @getDownloadFile 此方法对应的是Struts.xml文件中的:
* <param name="inputName">downloadFile</param>
* 返回下载文件的流、可以参看Struts2的源码
*/
public InputStream getDownloadFile(){
this.setFileName();
return ServletActionContext.getServletContext().getResourceAsStream("/"+"images/"+fileRealName);
}
@Override
public String execute() throws Exception{
return SUCCESS;
}
}
上传jsp页面:
[xhtml] view plaincopyprint?<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>My JSP 'upload.jsp' starting page</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
-->
</head>
<body>
<formaction="upload.action"method="post"enctype="multipart/form-data">
<table>
<tr>
<td>上传文件</td>
<td>标题:<inputtype="text"name="uploadFileName"/>
<inputtype="file"name="upload"/><br/>
标题:<inputtype="text"name="uploadFileName"/>
<inputtype="file"name="upload"/><br/>
标题:<inputtype="text"name="uploadFileName"/>
<inputtype="file"name="upload"/><br/>
标题:<inputtype="text"name="uploadFileName"/>
<inputtype="file"name="upload"/><br/>
标题:<inputtype="text"name="uploadFileName"/>
<inputtype="file"name="upload"/>
</td>
</tr>
<tr>
<td><inputtype="submit"value="提交"/></td>
<td><inputtype="reset"value="重置"/></td>
</tr>
</table>
</form>
</body>
</html>
下载jsp页面:
[xhtml] view plaincopyprint?<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%>
<%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>My JSP 'download.jsp' starting page</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
-->
</head>
<body>
<c:forEachitems="${uploadFiles}"var="files">
<imgsrc="images/${files.uploadRealName }"mce_src="images/${files.uploadRealName }"alt="ds"width="200px"height="300px"/>
<ahref="download.action?name=${files.uploadFileName }&realname=${files.uploadRealName }"mce_href="download.action?name=${files.uploadFileName }&realname=${files.uploadRealName }">${files.uploadFileName }</a><br/>
</c:forEach>
</body>
</html>
[xhtml] view plaincopyprint?<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
</web-app>
struts.xml配置:
[xhtml] view plaincopyprint?<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constantname="struts.i18n.encoding"value="utf-8"/>
<packagename="file"extends="struts-default">
<actionname="showUpload">
<result>/upload.jsp</result>
</action>
<actionname="upload"class="com.boxun.hzw.action.UploadAction">
<resultname="input">/upload.jsp</result>
<result>/download.jsp</result>
<interceptor-refname="fileUpload">
<paramname="maximumSize">2097152</param>
<paramname="addowedTypes">image/bmp,image/jpg</param>
</interceptor-ref>
<interceptor-refname="defaultStack"></interceptor-ref>
</action>
<actionname="download"class="com.boxun.hzw.action.DownloadAction">
<resultname="success"type="stream">
<paramname="contentDisposition">attachment;filename="${fileName}"</param>
<paramname="inputName">downloadFile</param>
</result>
</action>
</package>
</struts>
后台实体类代码:
[java] view plaincopyprint?package com.boxun.hzw.bean;
publicclass UploadFiles {
private String uploadContentType;
private String uploadFileName;
private String uploadRealName;
public String getUploadContentType() {
return uploadContentType;
}
publicvoid setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getUploadFileName() {
return uploadFileName;
}
publicvoid setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String getUploadRealName() {
return uploadRealName;
}
publicvoid setUploadRealName(String uploadRealName) {
this.uploadRealName = uploadRealName;
}
}
上传Action类:
[java] view plaincopyprint?package com.boxun.hzw.action;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.boxun.hzw.bean.UploadFiles;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("all")
publicclass UploadAction extends ActionSupport {
privatestaticfinallong serialVersionUID = 1L;
private File[] upload; //实际上传文件
private String[] uploadContentType; //文件的内容类型
private String[] uploadFileName; //上传文件名
private List<UploadFiles> uploadFiles = new ArrayList<UploadFiles>();
public String execute(){
String targetDirectory = ServletActionContext.getServletContext().getRealPath("/"+"images/");//获得路径
for(int i = 0 ; i < upload.length ; i++){
String fileName = uploadFileName[i]; //上传的文件名
String type = uploadContentType[i]; //文件类型
String realName = UUID.randomUUID().toString() +
getExt(fileName); //保存的文件名称、使用UUID+后缀进行保存
File target = new File(targetDirectory,realName);
try {
FileUtils.copyFile(upload[i],target);//上传至服务器的目录
} catch (IOException e) {
e.printStackTrace();
return INPUT;
}
//把路径()写入数据库 ---省略---
UploadFiles uf = new UploadFiles(); //创建文件
uf.setUploadContentType(type);
uf.setUploadFileName(fileName);
uf.setUploadRealName(realName);
uploadFiles.add(uf); //添加到需要下载文件的List集合中
}
ServletActionContext.getRequest().setAttribute("uploadFiles", uploadFiles);
return SUCCESS;
}
public File[] getUpload() {
return upload;
}
publicvoid setUpload(File[] upload) {
this.upload = upload;
}
public String[] getUploadContentType() {
return uploadContentType;
}
publicvoid setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String[] getUploadFileName() {
return uploadFileName;
}
publicvoid setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}
public List<UploadFiles> getUploadFiles() {
return uploadFiles;
}
publicvoid setUploadFiles(List<UploadFiles> uploadFiles) {
this.uploadFiles = uploadFiles;
}
publicstaticlong getSerialversionuid() {
return serialVersionUID;
}
publicstatic String getExt(String fileName){
return fileName.substring(fileName.lastIndexOf("."));
}
}
下载Action类:
[java] view plaincopyprint?package com.boxun.hzw.action;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("all")
publicclass DownloadAction extends ActionSupport {
privatestaticfinallong serialVersionUID = 6329383258366253255L;
private String fileName;
private String fileRealName;
publicvoid setFileName(){
//得到请求下载的文件名
String fname = ServletActionContext.getRequest().getParameter("name");
String frealname = ServletActionContext.getRequest().getParameter("realname");
try {
/*
* 对fname参数进行utf-8解码、注意:实际进行utf-8解码时会使用本地编码、本机为GBK。
* 这里使用reqeust.setCharacterEncoding解码无效.
* 只有解码了getDownloadFile()方法才能在下载目录下正确找到请求的文件
*/
fname = new String(fname.getBytes("ISO-8859-1"),"utf-8");
frealname = new String(frealname.getBytes("ISO-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
this.fileName = fname;
this.fileRealName = frealname;
}
/*
* @getFileName 此方法对应的是struts.xml文件中的:
* <param name ="contentDisposition"> attachment;filename="${fileName}"</param>
* 这个属性设置的是下载工具下载文件时显示的文件名、要想正确的显示中文文件名,
* 我们需要对fileName再次编码
* 否则中文名文件将出现乱码、或无法下载情况
* @return
*/
public String getFileName(){
try {
fileRealName = new String (fileRealName.getBytes(),"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return fileRealName;
}
/*
* @getDownloadFile 此方法对应的是Struts.xml文件中的:
* <param name="inputName">downloadFile</param>
* 返回下载文件的流、可以参看Struts2的源码
*/
public InputStream getDownloadFile(){
this.setFileName();
return ServletActionContext.getServletContext().getResourceAsStream("/"+"images/"+fileRealName);
}
@Override
public String execute() throws Exception{
return SUCCESS;
}
}
上传jsp页面:
[xhtml] view plaincopyprint?<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>My JSP 'upload.jsp' starting page</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
-->
</head>
<body>
<formaction="upload.action"method="post"enctype="multipart/form-data">
<table>
<tr>
<td>上传文件</td>
<td>标题:<inputtype="text"name="uploadFileName"/>
<inputtype="file"name="upload"/><br/>
标题:<inputtype="text"name="uploadFileName"/>
<inputtype="file"name="upload"/><br/>
标题:<inputtype="text"name="uploadFileName"/>
<inputtype="file"name="upload"/><br/>
标题:<inputtype="text"name="uploadFileName"/>
<inputtype="file"name="upload"/><br/>
标题:<inputtype="text"name="uploadFileName"/>
<inputtype="file"name="upload"/>
</td>
</tr>
<tr>
<td><inputtype="submit"value="提交"/></td>
<td><inputtype="reset"value="重置"/></td>
</tr>
</table>
</form>
</body>
</html>
下载jsp页面:
[xhtml] view plaincopyprint?<%@ page language="java"import="java.util.*"pageEncoding="UTF-8"%>
<%@ taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<basehref="<%=basePath%>">
<title>My JSP 'download.jsp' starting page</title>
<metahttp-equiv="pragma"content="no-cache">
<metahttp-equiv="cache-control"content="no-cache">
<metahttp-equiv="expires"content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description"content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
-->
</head>
<body>
<c:forEachitems="${uploadFiles}"var="files">
<imgsrc="images/${files.uploadRealName }"mce_src="images/${files.uploadRealName }"alt="ds"width="200px"height="300px"/>
<ahref="download.action?name=${files.uploadFileName }&realname=${files.uploadRealName }"mce_href="download.action?name=${files.uploadFileName }&realname=${files.uploadRealName }">${files.uploadFileName }</a><br/>
</c:forEach>
</body>
</html>
相关文章推荐
- Struts2 框架实现多文件上传下载
- Jimoshi_Struts2 框架学习(三)--valueStack和ognl、struts2验证、struts2文件上传和下载
- Spring整合Struts2实现多文件上传及下载
- struts2 实现文件上传和下载
- struts2 实现文件上传与下载
- struts2实现文件上传(多文件上传)及下载
- struts2实现文件的上传与下载
- Struts2 之 实现文件上传和下载
- Struts2实现文件上传和下载
- Struts2实现文件的上传和下载
- Struts2使用注解实现文件的上传与下载(一)
- Struts2(三)使用Struts2实现文件的上传和下载
- Struts2实现文件上传下载笔记
- SpringMVC框架实现文件、资源的上传和下载
- 框架(一)struts2——文件上传与下载
- java中struts2实现简单的文件上传与下载
- springmvc文件上传下载简单实现案例(ssm框架使用)
- 在SpringMVC框架下实现文件的上传和下载示例
- Struts2实现文件的上传和下载
- Struts2实现文件上传下载笔记