1. 程式人生 > >檔案上傳和下載(二)--【struts2】

檔案上傳和下載(二)--【struts2】

一、簡介

struts2在原有的上傳解析器繼承上做了進一步封裝,更進一步簡化了檔案上傳。

struts2預設使用的是Jakarta和Common-FileUpload的檔案上傳框架,因此,如果需要使用struts2的檔案上傳功能,則需要在web應用匯入相關jar包。

二、實現原理

1、Action需要使用3個屬性來封裝該檔案域的資訊:

(1)型別為File的xxx屬性封裝了該檔案域對應的檔案內容。

(2)型別為String的xxxFileName屬性封裝了改檔案域對應的檔案的檔案型別。

(3)型別為String的xxxContentType屬性封裝了該檔案域對應的檔案的型別。


2、配置struts.xml

struts.xml配置攔截器,設定允許上傳型別、檔案大小等資訊。

3、官網例子


三、專案實踐【myeclipse10】

專案目錄預覽


web.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
	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_3_0.xsd">
  <display-name>struts2</display-name>	
  
  <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>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

上傳action【Struts2UploadAction.java】
package com.wuhn.struts2.action;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author wuhn
 * @建立時間 2015-12-09
 * @功能 上傳
 * **/
public class Struts2UploadAction extends ActionSupport {
	private File image; //上傳的檔案  
	private String imageFileName; //檔名稱 要注意字首要和file的變數一樣
	private String imageContentType; //檔案型別 要注意字首要和file的變數一樣

    private String result;//返回資訊
    
	public File getImage() {
		return image;
	}

	public void setImage(File image) {
		this.image = image;
	}

	public String getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(String imageFileName) {
		this.imageFileName = imageFileName;
	}

	public String getImageContentType() {
		return imageContentType;
	}

	public void setImageContentType(String imageContentType) {
		this.imageContentType = imageContentType;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	@Override
    public String execute() throws Exception{
    	//設定儲存路徑
    	String path = ServletActionContext.getServletContext().getRealPath("/images");
    	File localFile = new File(path);
    	if(!localFile.exists()){
    		localFile.mkdir();
    	}
    	System.out.println("image:"+image);
    	System.out.println("imageFileName:"+imageFileName);
    	System.out.println("imageContentType:"+imageContentType);
    	System.out.println("檔案是否存在:"+image.exists());
    	//儲存檔案
		FileUtils.copyFile(image, new File(localFile, imageFileName));
		result = "上傳成功!";
    	
        return SUCCESS;
     }
    
}

下載action【Struts2DownloadAction.java】
package com.wuhn.struts2.action;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author wuhn
 * @建立時間 2015-12-09
 * @功能 下載
 * **/
public class Struts2DownloadAction extends ActionSupport{
	private String inputPath;//下載路徑 在struts.xml中配置

	private String filename;//下載檔名
	
	public String getInputPath() {
		return inputPath;
	}

	public void setInputPath(String inputPath) {
		this.inputPath = inputPath;
	}
	
	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	@Override
	public String execute() throws Exception {
		return SUCCESS;
	}
	
	public InputStream getInputStream() throws IOException{
		String path = ServletActionContext.getServletContext().getRealPath("/images");
		String filepath = path + "\\" +filename;
		File file = new File(filepath);
		return FileUtils.openInputStream(file);
		
		//return ServletActionContext.getServletContext().getResourceAsStream(inputPath);
	}
	
	public String getDownloadFileName(){
		String downloadFileName = "";
		//中文處理
		try {
			downloadFileName = URLEncoder.encode(filename, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return downloadFileName;
	}
}


批量上傳【BatchStruts2UploadAction.java】

package com.wuhn.struts2.action;

import java.io.File;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

/**
 * @author wuhn
 * @建立時間 2015-12-10
 * @功能 批量上傳
 * **/
public class BatchStruts2UploadAction extends ActionSupport {
	private List<File> image; //上傳的檔案  
	private List<String> imageFileName; //檔名稱 要注意字首要和file的變數一樣
	private List<String> imageContentType; //檔案型別 要注意字首要和file的變數一樣

    private String result;//返回資訊

	public List<File> getImage() {
		return image;
	}

	public void setImage(List<File> image) {
		this.image = image;
	}

	public List<String> getImageFileName() {
		return imageFileName;
	}

	public void setImageFileName(List<String> imageFileName) {
		this.imageFileName = imageFileName;
	}

	public List<String> getImageContentType() {
		return imageContentType;
	}

	public void setImageContentType(List<String> imageContentType) {
		this.imageContentType = imageContentType;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}
    
	@Override
    public String execute() throws Exception{
    	//設定儲存路徑
    	String path = ServletActionContext.getServletContext().getRealPath("/images");
    	File localFile = new File(path);
    	if(!localFile.exists()){
    		localFile.mkdir();
    	}
    	//迴圈儲存檔案
    	for (int i=0;i<image.size();i++) {
    		FileUtils.copyFile(image.get(i), new File(localFile, imageFileName.get(i)));
		}
		
		result = "上傳成功!";
    	
        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.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="true" />
    <!-- 該屬性指定需要Struts2處理的請求字尾,該屬性的預設值是action,即所有匹配*.action的請求都由Struts2處理。
        如果使用者需要指定多個請求字尾,則多個字尾之間以英文逗號(,)隔開。     -->
    <constant name="struts.action.extension" value="action" />
    <!-- 設定瀏覽器是否快取靜態內容,預設值為true(生產環境下使用),開發階段最好關閉 -->
    <constant name="struts.serve.static.browserCache" value="false" />
    <!-- 當struts的配置檔案修改後,系統是否自動重新載入該檔案,預設值為false(生產環境下使用),開發階段最好開啟 -->
    <constant name="struts.configuration.xml.reload" value="true" />
    <!-- 開發模式下使用,這樣可以打印出更詳細的錯誤資訊 -->
    <constant name="struts.devMode" value="true" />
    <!-- 預設的檢視主題 -->
    <constant name="struts.ui.theme" value="simple" />
    <!--<constant name="struts.objectFactory" value="spring" />-->
    <!--解決亂碼    -->
    <constant name="struts.i18n.encoding" value="UTF-8" />
    <!-- 指定允許上傳的檔案最大位元組數。預設值是2097152(2M) -->
    <constant name="struts.multipart.maxSize" value="10701096"/>
    <!-- 設定上傳檔案的臨時資料夾,預設使用javax.servlet.context.tempdir
    <constant name="struts.multipart.saveDir " value="d:/tmp" />
	 -->
	 <!-- 國際化 app_zh_CN.properties --> 
	<constant name="struts.custom.i18n.resources" value="app"></constant> 
	 
    <package name="default" namespace="/" extends="struts-default">
    	<!-- 上傳 -->
		<action name="upload" class="com.wuhn.struts2.action.Struts2UploadAction">
			<result name="success">/jsp/01.jsp</result>
			<result name="input">/jsp/error.jsp</result>
			
			<!-- 配置攔截器限制上傳檔案型別及大小 -->
			<interceptor-ref name="fileUpload">
				<!-- 檔案過濾 -->
				<param name="allowedTypes">image/png,image/gif,image/jpeg</param>
				<!-- 檔案大小, 以位元組為單位 -->
				<param name="maximumSize">10240000</param> 
			</interceptor-ref>
			<!-- 預設攔截器必須放在fileUpload之後,否則無效 -->
			<interceptor-ref name="defaultStack"></interceptor-ref>
		</action>
		
		
		<!-- 批量上傳 -->
		<action name="batchUpload" class="com.wuhn.struts2.action.BatchStruts2UploadAction">
			<result name="success">/jsp/03.jsp</result>
			<result name="input">/jsp/error.jsp</result>
			
			<!-- 配置攔截器限制上傳檔案型別及大小 -->
			<interceptor-ref name="fileUpload">
				<!-- 檔案過濾 -->
				<param name="allowedTypes">image/png,image/gif,image/jpeg</param>
				<!-- 檔案大小, 以位元組為單位 -->
				<param name="maximumSize">10240000</param> 
			</interceptor-ref>
			<!-- 預設攔截器必須放在fileUpload之後,否則無效 -->
			<interceptor-ref name="defaultStack"></interceptor-ref>
		</action>
		
		
		
		
		<!-- 下載 -->
		<action name="download" class="com.wuhn.struts2.action.Struts2DownloadAction">
			<!-- <param name="inputPath">images/20151026165425.png</param> -->
			<result name="success" type="stream">		   
			  <param name="contentType">application/octet-stream</param>
			  <param name="inputName">inputStream</param>
			  <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>
			  <param name="bufferSize">1024</param>
			</result>			
		</action>
		
			
		
    </package>
	
	<!-- 
    <include file="example.xml"/>
	 -->

</struts>

頁面

1、上傳頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE>
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>上傳</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">
	-->

  </head>
  	
  <body>
    	<form action="<%=path%>/upload.action" method="post" enctype="multipart/form-data">
    		上傳檔案:<input type="file" name="image"/>
    		<input type="submit" value="提交"/>${result}
    	</form>
  </body>
</html>

2、下載頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE>
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>下載</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">
	-->

  </head>
  
  <body>
    下載檔案<a href="<%=path%>/download.action?filename=20151026165425.png">檔案</a>
  </body>
</html>

3、批量上傳
<%@ 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>批量上傳</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">
	-->

  </head>
  
  <body>
    <form action="<%=path%>/batchUpload.action" method="post" enctype="multipart/form-data">
    		上傳檔案1:<input type="file" name="image"/>
    		上傳檔案2:<input type="file" name="image"/>
    		上傳檔案3:<input type="file" name="image"/>
    		<input type="submit" value="提交"/>${result}
    	</form>
  </body>
</html>

這裡還做了一個上傳erro統一處理頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE>
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'error.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">
	-->

  </head>
  
  <body>
    	錯誤:<s:fielderror></s:fielderror>
  </body>
</html>
配置一個properties