您的位置:首页 > 编程语言 > Java开发

Struts2 框架实现多文件上传下载

2013-01-11 14:57 549 查看
web.xml配置:

[xhtml]
view plaincopyprint?

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="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?

<?xml version="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>

<constant name="struts.i18n.encoding" value="utf-8" />

<package name="file" extends="struts-default">
<action name="showUpload">
<result>/upload.jsp</result>
</action>

<action name="upload" class="com.boxun.hzw.action.UploadAction">
<result name="input">/upload.jsp</result>
<result>/download.jsp</result>
<interceptor-ref name="fileUpload">
<param name="maximumSize">2097152</param>
<param name="addowedTypes">image/bmp,image/jpg</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</action>

<action name="download" class="com.boxun.hzw.action.DownloadAction">
<result name="success" type="stream">
<param name="contentDisposition">attachment;filename="${fileName}"</param>
<param name="inputName">downloadFile</param>
</result>
</action>

</package>
</struts>

后台实体类代码:

[java]
view plaincopyprint?

package com.boxun.hzw.bean;

public class UploadFiles {
private String uploadContentType;

private String uploadFileName;

private String uploadRealName;

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 String getUploadRealName() {
return uploadRealName;
}

public void 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")
public class UploadAction extends ActionSupport {
private static final long 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;
}

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 List<UploadFiles> getUploadFiles() {
return uploadFiles;
}

public void setUploadFiles(List<UploadFiles> uploadFiles) {
this.uploadFiles = uploadFiles;
}

public static long getSerialversionuid() {
return serialVersionUID;
}

public static 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")
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。
* 这里使用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>
<base href="<%=basePath%>">

<title>My JSP 'upload.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
-->

</head>

<body>
<form action="upload.action" method="post" enctype="multipart/form-data">
<table>
<tr>
<td>上传文件</td>
<td>标题:<input type="text" name="uploadFileName" />
<input type="file" name="upload" /><br/>
标题:<input type="text" name="uploadFileName" />
<input type="file" name="upload" /><br/>
标题:<input type="text" name="uploadFileName" />
<input type="file" name="upload" /><br/>
标题:<input type="text" name="uploadFileName" />
<input type="file" name="upload" /><br/>
标题:<input type="text" name="uploadFileName" />
<input type="file" name="upload" />
</td>
</tr>
<tr>
<td><input type="submit" value="提交"/></td>
<td><input type="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>
<base href="<%=basePath%>">

<title>My JSP 'download.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
-->

</head>

<body>
<c:forEach items="${uploadFiles}" var="files">
<img src="images/${files.uploadRealName }" mce_src="images/${files.uploadRealName }" alt="ds" width="200px" height="300px" />
<a href="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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: