第一次使用struts架構進行實作檔案上傳和下載下傳,實作檔案上傳很簡單,但是檔案下載下傳好多地方需要注意。與大家共勉,共同進步
首先,建立建立檔案上傳的功能
導入的jar包
asm-3.3.jar
asm-commons-3.3.jar
asm-tree-3.3.jar
commons-fileupload-1.3.1.jar
commons-io-2.2.jar
commons-lang3-3.2.jar
freemarker-2.3.22.jar
javassist-3.11.0.GA.jar
log4j-api-2.2.jar
log4j-core-2.2.jar
ognl-3.0.6.jar
struts2-core-2.3.24.1.jar
struts2-dojo-plugin-2.3.24.1.jar
xwork-core-2.3.24.1.jar
大家也可以用maven,由于我是用maven進行依賴包控制,強烈建議大家學習maven,可以節省很多記憶體,而且不用手動導包哦。
先把pom.xml檔案發給你看應該導入哪些jar包吧
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>yozo</groupId>
<artifactId>upload</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<struts2.version>2.3.24</struts2.version>
</properties>
<dependencies>
<!-- struts2 begin -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts2.version}</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>${struts2.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- struts2 end -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path></path>
<port>8888</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
建立uploadfile.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>
<form action="${pageContext.request.contextPath }/fileUploadAction" method="post" enctype="multipart/form-data">
檔案名:<input type="text" name="filename"/><br/>
檔案:<input type="file" name="file1"/><br/>
<input type="submit" value="上傳檔案">
</form>
</body>
</html>
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnLxkzN5QzNykDMxETMwkTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
enctype="multipart/form-data"表示不對字元編碼。在使用包含檔案上傳控件的表單時,必須使用該值。
建立error.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>
error.jsp
<!-- 查詢struts2在運作期間産生的所有錯誤資訊 -->
<%@ taglib prefix="s" uri="/struts-tags"%>
<s:fielderror></s:fielderror>
</body>
</html>
建立UploadAction類
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport{
private static final long serialVersionUID = 1L;
//對應表單的file1 <input type="file" name="file1"/>
private File file1;
//目前上傳的檔案名
private String file1FileName;
//檔案類型(MIME)
private String file1ContentType;
public void setFile1(File file1) {
this.file1 = file1;
}
public void setFile1FileName(String file1FileName) {
this.file1FileName = file1FileName;
}
public void setFile1ContentType(String file1ContentType) {
this.file1ContentType = file1ContentType;
}
@Override
public String execute() throws Exception {
//設定上傳的路徑
String path=ServletActionContext.getServletContext().getRealPath("/upload");
//設定上傳檔案的名字
File destFile=new File(path,file1FileName);
//檔案copy
FileUtils.copyFile(file1, destFile);
return SUCCESS;
}
}
建立strutsxml檔案
這裡的檔案内容已經設定檔案上傳和檔案下載下傳
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- 修改上傳檔案的最大大小為30M -->
<constant name="struts.multipart.maxSize" value="31457280"></constant>
<!-- 聲明包 -->
<package name="fileuploadpackage" extends="struts-default">
<!-- 定義action -->
<action name="fileUploadAction" class="UploadAction">
<!-- 顯示成功的jsp頁面 ,重定向到action-->
<result name="success" type="redirectAction">
down_list
</result>
<!-- 檔案上傳攔截器,限制運作上傳的檔案的類型,還有其他一個方法,這是其中一個 -->
<!--FileUploadInterceptor相關檔案攔截參數且看該類-->
<interceptor-ref name="defaultStack">
<!-- 限制運作的檔案的擴充名 fileUpload.allowedExtensions固定寫法
allowedExtensions找到allowedExtensionsSet去掉set即可-->
<param name="fileUpload.allowedExtensions">txt,jpg,gif,png</param>
</interceptor-ref>
<!-- 錯誤提示,INPUT:Action的執行,需要從前端界面擷取參數,INPUT就是代表這個參數輸入的界面,
一般在應用中,會對這些參數進行驗證,如果驗證沒有通過,将自動傳回到該視圖; -->
<result name="input">error.jsp</result>
</action>
<!-- 下載下傳的action -->
<action name="down_*" class="DownAction" method="{1}">
<!-- 清單展示 -->
<result name="list">list.jsp</result>
<!-- 下載下傳操作 -->
<result name="download" type="stream">
<!-- 相關的參數,請搜尋StreamResult類,在Strutsjar包中 -->
<!--contentType表明資料包裡面發送的資料類型,是以流的形式下載下傳檔案,這樣可以實作任意格式的檔案下載下傳。-->
<param name="contentType">application/octet-stream</param>
<!-- 對應的就是Action種的屬性,傳回流的屬性,就是action的GetAttrInputStream方法 -->
<param name="inputName">attrInputStream</param>
<!-- 下載下傳頭,包括:浏覽器顯示的檔案名 -->
<!--attachment表示顯示下載下傳框下載下傳,預設是inline-->
<!--filename表示放在下載下傳框裡面的名字${downFileName}是擷取getDownFileName裡面的傳回值-->
<param name="contentDisposition">inline;filename="${downFileName}"</param>
<!-- 緩沖區大小設定 -->
<param name="bufferSize">1024</param>
</result>
</action>
</package>
</struts>
如果你隻是想實作檔案上傳功能,跳轉一個成功的頁面,你可以把type屬性去掉,因為type屬性預設值是轉發。然後裡面寫入一個頁面的相對路徑就好類
建立一個web.xml放在webapp/WEB_INF下面
WEB-INF的内容是不能讓用戶端直接擷取的
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_upload20170306</display-name>
<welcome-file-list>
<welcome-file>uploadfile.jsp</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>
<!-- 其他過濾器 -->
<!-- 引入struts2的核心過濾器 -->
<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>
注意這裡的核心過濾器的名字不要寫錯,否則會出現很多問題。你可以先查找到該類,然後進行複制
通過以上的方法,就可以實作檔案上傳了
下載下傳功能
首先先編寫響應的list.jsp頁面顯示檔案的頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!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>
<center>
<table cellpadding="10" cellspacing="10">
<tr>
<td>編号</td>
<td>檔案名</td>
<td>操作</td>
</tr>
<c:forEach items="${fileNames }" var="fileName" varStatus="fn">
<tr>
<td>${fn.count}</td>
<td>
${fileName}<a href="down_down.action?fileName=${fileName}" target="_blank" rel="external nofollow" >下載下傳</a><br>
</td>
</tr>
</c:forEach>
</table>
</center>
</body>
</html>
Action建立的時候傳回的filename是一個數組,是以需要周遊
編寫一個DownAction類
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownAction extends ActionSupport{
private static final long serialVersionUID = 1L;
//檔案的清單
public String list() throws Exception {
//獲得檔案路徑
String path=ServletActionContext.getServletContext().getRealPath("/upload");
//獲得目錄的對象
File file=new File(path);
//獲得目錄裡面是以檔案的檔案名
String[] fileNames=file.list();
ActionContext ac=ActionContext.getContext();
//獲得request域
Map<String,Object> request=(Map<String,Object>)ac.get("request");
request.put("fileNames", fileNames);
return "list";
}
//檔案下載下傳
private String fileName;
//更改因為中文會出現亂碼,是以需要轉碼
public void setFileName(String fileName) {
//處理傳入的參數種問題(get送出)
try {
fileName=new String(fileName.getBytes("ISO8859-1"),"UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException();
}
this.fileName = fileName;
}
//這個是頁面要跳轉的方法
public String down() throws Exception {
return "download";
}
//傳回流的方法
public InputStream getAttrInputStream(){
return ServletActionContext.getServletContext().getResourceAsStream("/upload/"+fileName);
}
//下載下傳顯示的中文名,遊覽器顯示的中文名
public String getDownFileName(){
try{
//需要導入URLEncoder包
fileName = URLEncoder.encode(fileName,"UTF-8");
}catch(Exception e){
throw new RuntimeException();
}
return fileName;
}
}
==由于上面我已經把struts.xml檔案拿出來了。是以為這裡就截圖一下,相關的配置==
![在這裡插入圖檔描述](https://img-blog.csdnimg.cn/20190111101529455.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM3MzEyNTU1,size_16,color_FFFFFF,t_70)
#### 以上已經實作了檔案上傳和下載下傳功能,響應的注解已經在代碼裡面說明清楚。相關的代碼,我已經達成war,可直接運作