实现功能:
文件上传后点击链接进行下载已上传文件(单文件)
文件下载前校验是否登陆,登陆后才可进行下载
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Struts2_demo1</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.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>/*</url-pattern>
</filter-mapping>
</web-app>
上传页面(单文件) uploadForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>文件上传</title>
</head>
<body>
<s:fielderror/>
<form action="upload" method="post" enctype="multipart/form-data">
文件标题:<input type="text" name="title" /><br>
选择文件:<input type="file" name="upload" /><br>
<input type="submit" value="提交"/>
</form>
</body>
</html>
单文件上传成功页面 success.jsp(超链接下载)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传成功</title>
</head>
<body>
上传成功!<br>
<s:property value=" + title"/>
文件为:<img src =' upload/<s:property value="uploadFileName"/> '/> <br>
<a href="download?downfilename=<s:property value="uploadFileName"/>
&inputPath=/upload/<s:property value="uploadFileName"/>">下载</a>
</body>
</html>
多文件上传页面: uploadForm-List.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>使用List上传多个文件</title>
</head>
<body>
<s:fielderror/>
<form action="upload-list" 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>
多文件上传成功页面 success-list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传成功</title>
</head>
<body>
上传成功!<br>
<!-- 输出上传的表单里的文件标题属性 -->
文件标题:<s:property value=" + title"/><br>
<s:iterator value="uploadFileName" var="imageFile">
<!-- 根据上传文件的文件名,在页面上显示上传的图片 -->
文件为:<img src='upload/${imageFile}'/><br>
</s:iterator>
</body>
</html>
登陆页面 loginForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>下载前的登录页面</title>
</head>
<body>
<h3>下载前的登录页面</h3>
${requestScope.tip}
<form action="login" method="POST" >
用户名:<input type="text" name="user"/><br/>
密码:<input type="password" name="pass"/><br/>
<input type="submit" value="登录"/><br/>
</form>
</body>
</html>
单文件上传实现类 UploadAction.java
import java.io.*;
import java.util.UUID;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private String title; // 封装文件标题请求参数的属性
private File upload; // 封装上传文件域的属性
private String uploadContentType; // 封装上传文件名的属性
private String uploadFileName; // 在xml文件中配置值的方法
private String savePath; // 接受Struts.xml文件中配置值的方法
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
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 String getSavePath() {
return ServletActionContext.getRequest().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String execute() throws Exception {
String newName = UUID.randomUUID() + uploadFileName.substring(uploadFileName.lastIndexOf("."));
// 以服务器的文件保存地址和随机文件名建立上传文件输出流
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + newName);
FileInputStream fis = new FileInputStream(getUpload()); // 读文件
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
setUploadFileName(newName);
return SUCCESS;
}
}
多文件上传实现类 UploadAction2.java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.UUID;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction2 extends ActionSupport {
private String title;
// 使用List集合封装多个文件域对应的文件内容
private List<File> upload;
// 使用List集合封装多个文件域对应的文件类型
private List<String> uploadContentType;
// 使用List集合封装多个文件域对应的文件名字
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 {
// 遍历每个需要上传的文件
for (int i = 0; i < getUpload().size(); i++) {
String newName = UUID.randomUUID()
+ uploadFileName.get(i).substring(uploadFileName.get(i).lastIndexOf("."));
// 以服务器的文件保存地址和随机文件名建立上传文件输出流
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + newName);
// 以每个需要上传的文件建立文件输入流
FileInputStream fis = new FileInputStream(getUpload().get(i));
// 将每个需要上传的文件写到服务器对应的文件中
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
getUploadFileName().set(i, newName);
}
return SUCCESS;
}
}
文件下载实现类 FileDownloadAction.java
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class FileDownloadAction extends ActionSupport {
private String inputPath; // 下载文件的资源路径
private String downfilename;// 下载文件的文件名
public String getInputPath() {
return inputPath;
}
public void setInputPath(String inputPath) throws Exception {
// 处理请求参数的编码
this.inputPath = new String(inputPath.getBytes("ISO-8859-1"), "UTF-8");
}
public String getDownfilename() {
String downfilename = ServletActionContext.getRequest().getParameter("downfilename");
try {
downfilename = new String(downfilename.getBytes("ISO-8859-1"), "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
return downfilename;
}
public void setDownfilename(String downfilename) throws Exception {
this.downfilename = new String(inputPath.getBytes("ISO-8859-1"), "UTF-8");
}
/*
* 定义一个返回InputStream的方法, 该方法将作为被下载文件的入口, 且需要配置stream类型结果时指定inputName参数,
* inputName参数的值就是方法去掉get前缀、首字母小写的字符串
*/
public InputStream getTargetFile() throws Exception {
// ServletContext提供getResourceAsStream()方法
// 返回指定文件对应的输入流
//System.out.println(inputPath);
//System.out.println(getDownfilename());
//System.out.println(downfilename);
// InputStream
// in=ServletActionContext.getServletContext().getResourceAsStream(getInputPath());
// System.out.println(in);
return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
}
public String execute() {
// 取得ActionContext实例
ActionContext ctx = ActionContext.getContext();
// 通过ActionContext访问用户的HttpSession
String user = (String) ctx.getSession().get("user");
// 判断Session里的user是否通过检查
if (user != null && user.equals("admin")) {
return SUCCESS;
}
ctx.put("tip", "您还没有登录,或用户名不正确,请重新登录!");
return LOGIN;
}
}
登陆实现类 LoginAction.java
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
public class LoginAction implements Action {
// 封装请求参数的两个属性
private String user;
private String pass;
// user的setter和getter方法
public void setUser(String user) {
this.user = user;
}
public String getUser() {
return this.user;
}
// pass的setter和getter方法
public void setPass(String pass) {
this.pass = pass;
}
public String getPass() {
return this.pass;
}
public String execute() {
ActionContext.getContext().getSession().put("user", getUser());
return SUCCESS;
}
}
struts.xml 文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="uploads" extends="struts-default">
<action name="upload" class="nuc.lj.action.UploadAction">
<!-- 动态设置Action的属性值 -->
<param name="savePath">/upload</param>
<!-- 配置input逻辑视图对应的视图页面 -->
<result name="input">/uploadForm.jsp</result>
<result>/success.jsp</result>
</action>
<action name="upload-list" class="nuc.lj.action.UploadAction2">
<!-- 动态设置Action的属性值 -->
<param name="savePath">/upload-list</param>
<!-- 配置input逻辑视图对应的视图页面 -->
<result name="input">/uploadForm-list.jsp</result>
<result>/success-list.jsp</result>
</action>
<action name="download" class="nuc.lj.action.FileDownloadAction">
<!-- 配置类型为stream 用于向浏览器返回InputStream的结果类型(文件下载) -->
<result name="success" type="stream">
<param name="contentType">application/octet-stream;charset=ISO-8859-1</param>
<param name="inputName">targetFile</param>
<param name="contentDisposition">attachment;filename="${downfilename}"</param>
<param name="bufferSize">4096</param>
</result>
<result name="login">/loginForm.jsp</result>
</action>
<action name="*">
<result>/{1}.jsp</result>
</action>
</package>
</struts>
未实现功能:多文件上传后进行多文件打包下载,待补充。