三、 同时上传多个文件
Struts 2 很方便实现多个文件上传,这个和之前上传单个文件并没有太大区别。
下面介绍使用 数组 和 List 处理同时上传多个文件的方式
3.1 使用数组同时上传多个文件
如果页面上有 3 个文件上传,正如前面介绍,当然可以为上传页面中的每个文件域指定 3 个属性:文件名、文件类型、文件内容。但这样会使代码臃肿,编程复杂化。
因此,下面以数组来封装 3 个文件域。为了让数组一次封装 3 个文件域,需要将 3 个文件域的 name 设置成相同的 。如下:
upload.jsp
<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>使用数组上传多个文件</title>
<meta name="website" content="http://www.crazyit.org" />
</head>
<body>
<span style="color:red"><s:fielderror/></span>
<form action="upload.action" method="post"
enctype="multipart/form-data">
文件标题:<input type="text" name="title" /><br />
选择第一个文件:<input type="file" name="upload" /><br />
选择第二个文件:<input type="file" name="upload" /><br />
选择第三个文件:<input type="file" name="upload" /><br />
<input value="上传" type="submit" />
</form>
</body>
</html>
下面需要 3 个数组分别封装文件名、文件类型、文件内容
UploadAction.java
import com.opensymphony.xwork2.Action;
import org.apache.struts2.ServletActionContext;
import java.io.File;
import java.io.*;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport
{
private String title;
//使用File数组封装多个文件域对应的文件内容
private File[] upload;
//使用字符串数组封装多个文件域对应的文件类型
private String[] uploadContentType;
//使用字符串数组封装多个文件域对应的文件名字
private String[] uploadFileName;
//接受依赖注入的属性
private String savePath;
//title属性的setter和getter方法
public void setTitle(String title)
{
this.title = title;
}
public String getTitle()
{
return this.title;
}
//upload属性的setter和getter方法
public void setUpload(File[] upload)
{
this.upload = upload;
}
public File[] getUpload()
{
return this.upload;
}
//uploadContentType属性的setter和getter方法
public void setUploadContentType(String[] uploadContentType)
{
this.uploadContentType = uploadContentType;
}
public String[] getUploadContentType()
{
return this.uploadContentType;
}
//uploadFileName属性的setter和getter方法
public void setUploadFileName(String[] uploadFileName)
{
this.uploadFileName = uploadFileName;
}
public String[] getUploadFileName()
{
return this.uploadFileName;
}
//savePath属性的setter和getter方法
public void setSavePath(String savePath)
{
this.savePath = savePath;
}
public String getSavePath()
{
return ServletActionContext.getRequest()
.getRealPath(savePath);
}
@Override
public String execute() throws Exception
{
//取得需要上传的文件数组
File[] files = getUpload();
//遍历每个需要上传的文件
for (int i = 0 ; i < files.length ; i++)
{
//以服务器的文件保存地址和原文件名建立上传文件输出流
FileOutputStream fos = new FileOutputStream(
getSavePath() + "\\" + getUploadFileName()[i]);
//以每个需要上传的文件建立文件输入流
FileInputStream fis = new FileInputStream(files[i]);
//将每个需要上传的文件写到服务器对应的文件中
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0)
{
fos.write(buffer , 0 , len);
}
fos.close();
}
return SUCCESS;
}
}
struts.xml
<?xml version="1.0" encoding="GBK"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <!-- 指定国际化资源文件的baseName为globalMessages --> <constant name="struts.custom.i18n.resources" value="globalMessages"/> <!-- 设置该应用使用的解码集 --> <constant name="struts.i18n.encoding" value="GBK"/> <package name="lee" extends="struts-default"> <!-- 配置处理文件上传的Action --> <action name="upload" class="lee.UploadAction"> <!-- 配置fileUpload的拦截器 --> <interceptor-ref name="fileUpload"> <!-- 配置允许上传的文件类型 --> <param name="allowedTypes">image/bmp,image/png, image/gif,image/jpeg</param> <!-- 配置允许上传的文件大小 --> <param name="maximumSize">2000000</param> </interceptor-ref> <!-- 配置系统默认的拦截器 --> <interceptor-ref name="defaultStack"/> <!-- 动态设置Action的属性值 --> <param name="savePath">/upload</param> <!-- 配置input逻辑视图对应的视图页面 --> <result name="input">/upload.jsp</result> <!-- 配置Struts 2默认的视图页面 --> <result>/succ.jsp</result> </action> <action name=""> <result>.</result> </action> </package> </struts>
配置 Action 与前面配置上传单个文件的 Action 没有什么区别
Struts 2 系统负责将 3 个文件域对应的文件内容、文件名、文件类型,对应放入 Action 实例中的文件内容数组、文件名数组、文件类型数组中,这个过程无需开发者关心。Struts 2 简单易用!
3.2 使用 List 同时上传多个文件
和使用数组差不多
UploadAction.java
import org.apache.struts2.ServletActionContext;
import java.io.File;
import java.io.*;
import java.util.*;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private String title;
// 使用File数组封装多个文件域对应的文件内容
private List<File> upload;
// 使用字符串数组封装多个文件域对应的文件类型
private List<String> uploadContentType;
// 使用字符串数组封装多个文件域对应的文件名字
private List<String> uploadFileName;
// 接受依赖注入的属性
private String savePath;
// title属性的setter和getter方法
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return this.title;
}
// upload属性的setter和getter方法
public void setUpload(List<File> upload) {
this.upload = upload;
}
public List<File> getUpload() {
return this.upload;
}
// uploadContentType属性的setter和getter方法
public void setUploadContentType(List<String> uploadContentType) {
this.uploadContentType = uploadContentType;
}
public List<String> getUploadContentType() {
return this.uploadContentType;
}
// uploadFileName属性的setter和getter方法
public void setUploadFileName(List<String> uploadFileName) {
this.uploadFileName = uploadFileName;
}
public List<String> getUploadFileName() {
return this.uploadFileName;
}
// savePath属性的setter和getter方法
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String getSavePath() {
return ServletActionContext.getRequest().getRealPath(savePath);
}
@Override
public String execute() throws Exception {
// 取得需要上传的文件数组
List<File> files = getUpload();
// 遍历每个需要上传的文件
for (int i = 0; i < files.size(); i++) {
// 以服务器的文件保存地址和原文件名建立上传文件输出流
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\"
+ getUploadFileName().get(i));
// 以每个需要上传的文件建立文件输入流
FileInputStream fis = new FileInputStream(files.get(i));
// 将每个需要上传的文件写到服务器对应的文件中
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
}
return SUCCESS;
}
}
对于 Struts 2 而言,使用泛型限制的 List 与数组的作用几乎相同
四、 使用 Struts 2 控制文件下载
① Struts 2 提供了 stream 结果类型,专门用于支持文件下载功能 。
② 指定 stream 结果类型时,需要指定一个 inputName 参数,该参数指定一个输入流 ,这个输入流是被下载文件的入口。
③ 通过 Struts 2的文件下载支持,允许系统控制浏览者下载文件的权限,包括实现文件名为非西欧字符的文件下载。
4.1 实现文件下载的 Action
一般情况只要在页面给出一个超链接,该超链接的 href 属性等于要下载文件的文件名,就可以下载了,但是如果文件名是中文,会导致下载失败;如果应用程序需要在用户下载之前进一步检查,比如判断权限等。
rawDown.html
<body>
<h3>Struts 2的文件下载</h3>
<ul>
<li>下载疯狂Java联盟的Logo:
<a href="images/疯狂Java联盟.gif">下载图形文件</a></li>
<li>下载疯狂Java联盟的Logo的压缩文件:
<a href="images/crazyit.zip">下载压缩文件</a></li>
</ul>
</body>
第一个文件是中文,所以会报错(404)
为了解决这个问题 ,我们使用 Struts 2 文件下载。
文件下载的 Action 与 普通 Action 并没太大的不同, 仅仅是该 Action 需要提供一个返回 InputStream 流的方法,该方法代表了被下载文件的入口:
FileDownloadAction.java
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileDownloadAction extends ActionSupport {
// 该属性是依赖注入的属性,可以在配置文件中动态指定该属性值
private String inputPath;
// 依赖注入该属性值的setter方法
public void setInputPath(String value) {
inputPath = value;
}
/*
* 定义一个返回InputStream的方法, 该方法将作为被下载文件的入口, 且需要配置stream类型结果时指定inputName参数,
* inputName参数的值就是方法去掉get前缀、首字母小写的字符串
*/
public InputStream getTargetFile() throws Exception {
// ServletContext提供getResourceAsStream()方法
// 返回指定文件对应的输入流
return ServletActionContext.getServletContext().getResourceAsStream(
inputPath);
}
}
该 Action 中包含一个 getTargetFile() 方法,返回一个 InputStream 输入流,则 stream 类型的结果映射中 inputName 参数值为 targetFile
4.2 配置 Action
配置该 Action 关键是需要配置一个类型为 stream 的结果,该 stream 类型的结果将使用文件下载作为响应。
stream类型结果要指定 4 个属性 :
● contentType : 指定被下载文件的文件类型
● inputName : 指定被下载文件的入口输入流
● contentDisposition : 指定下载的文件名
● bufferSize : 指定下载文件时的缓冲大小。
stream 结果类型的逻辑视图是返回给客户端一个输入流,因此无需指定 location 属性。
提示 : 在配置 stream 类型的结果时,因为无需指定实际显示的物理资源,所以无需指定 location 属性,只需要指定 inputName 属性即可,该属性代表被下载文件的入口
struts.xml
<?xml version="1.0" encoding="GBK"?> <!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.custom.i18n.resources" value="globalMessages"/> <constant name="struts.i18n.encoding" value="GBK"/> <package name="lee" extends="struts-default"> <action name="download" class="lee.FileDownloadAction"> <!-- 指定被下载资源的位置 --> <param name="inputPath">\images\疯狂Java联盟.gif</param> <!-- 配置结果类型为stream的结果 --> <result name="success" type="stream"> <!-- 指定下载文件的文件类型 --> <param name="contentType">image/gif</param> <!-- 指定由getTargetFile()方法返回被下载文件的InputStream --> <param name="inputName">targetFile</param> <param name="contentDisposition">filename="crazyit.gif"</param> <!-- 指定下载文件的缓冲大小 --> <param name="bufferSize">4096</param> </result> </action> <action name="download2" class="lee.AuthorityDownAction"> <!-- 定义被下载文件的物理资源 --> <param name="inputPath">\images\crazyit.zip</param> <result name="success" type="stream"> <!-- 指定下载文件的文件类型 --> <param name="contentType">application/zip</param> <!-- 指定由getTargetFile()方法返回被下载文件的InputStream --> <param name="inputName">targetFile</param> <param name="contentDisposition">filename="crazyit.zip"</param> <!-- 指定下载文件的缓冲大小 --> <param name="bufferSize">4096</param> </result> <!-- 定义一个名为login的结果 --> <result name="login">/input.jsp</result> </action> <action name="login" class="lee.LoginAction"> <result>/stuts2Down.html</result> </action> <action name=""> <result>.</result> </action> </package> </struts>
上面 download 提供文件下载支持,可以实现包含中文文件名的文件下载了。
<body>
<h1>Struts2的文件下载</h1>
<ul>
<li>
下载Struts2的Logo:<a href="download.action">下载图形文件</a>
</li>
</ul>
</body>
采用如上方式的超链接即可实现文件下载了。
4.3 下载前的授权控制 权限
应用程序可以在用户下载文件前,先通过 Action 来检查用户是否有权限下载该文件,就可以实现下载前的授权控制。
AuthorityDownAction.java
package lee;
import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import java.util.Map;
public class AuthorityDownAction implements Action {
private String inputPath;
public void setInputPath(String value) {
inputPath = value;
}
public InputStream getTargetFile() throws Exception {
// ServletContext提供getResourceAsStream()方法
// 返回指定文件对应的输入流
return ServletActionContext.getServletContext().getResourceAsStream(
inputPath);
}
public String execute() throws Exception {
// 取得ActionContext实例
ActionContext ctx = ActionContext.getContext();
// 通过ActionContext访问用户的HttpSession
Map session = ctx.getSession();
String user = (String) session.get("user");
// 判断Session里的user是否通过检查
if (user != null && user.equals("crazyit")) {
return SUCCESS;
}
ctx.put("tip", "您还没有登录,或者登录的用户名不正确,请重新登录!");
return LOGIN;
}
}
struts.xml
<action name="download2" class="lee.AuthorityDownAction"> <!-- 定义被下载文件的物理资源 --> <param name="inputPath">\images\crazyit.zip</param> <result name="success" type="stream"> <!-- 指定下载文件的文件类型 --> <param name="contentType">application/zip</param> <!-- 指定由getTargetFile()方法返回被下载文件的InputStream --> <param name="inputName">targetFile</param> <param name="contentDisposition">filename="crazyit.zip"</param> <!-- 指定下载文件的缓冲大小 --> <param name="bufferSize">4096</param> </result> <!-- 定义一个名为login的结果 --> <result name="login">/input.jsp</result> </action>
上面 Action 在下载前先进行权限检查,如果要下载文件的浏览者没有登录,或者用户名不是 crazyit, Action 将返回一个 input.jsp
input.jsp
<%@ page contentType="text/html;charset=GBK"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> 下载前的登录页面 </TITLE>
</HEAD>
<BODY>
<h3>下载前的登录页面</h3>
${requestScope.tip}
<FORM METHOD="POST" ACTION="login.action">
用户名:<INPUT TYPE="text" NAME="user"/><br>
密码:<INPUT TYPE="text" NAME="pass"/><br>
<INPUT TYPE="submit" value="登录"/><br>
</FORM>
</BODY>
</HTML>
strutsDown.html
<li>
下载Struts2的Logo的压缩文件:<a href="download2.action">下载压缩文件</a>
</li>