1. 程式人生 > >Spring整合Struts2實現多檔案上傳及下載

Spring整合Struts2實現多檔案上傳及下載

Sping與Struts環境的搭建在前文已經講述過了,再次就不再做過多介紹了,詳情請參考前文《Spring整合Struts2中攔截鏈與註解的使用 》。接下來進入正題,Struts2的多檔案上傳步驟。本文仍然沿用Spring框架對Struts2框架進行管理,首先來看web.xml檔案:

<?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">
  <display-name></display-name>	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>classpath:config/applicationContext-*.xml</param-value>
  </context-param>
  
   <filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    <init-param>
    	<param-name>config</param-name>
    	<param-value>struts-default.xml,struts-plugin.xml,config/struts.xml</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>struts2</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>


為了方便維護,我將一般常用變數放入struts.xml檔案,通過include標籤將struts-upload.xml檔案引入到struts.xml檔案中,其配置內容分別如下:

<?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.xml檔案 -->
<struts>
	<include file="config/struts-upload.xml"></include>

	<constant name="struts.action.extension" value=","></constant>
	<!-- 上傳檔案是所允許的檔案最大值 -->
	<constant name="struts.multipart.maxSize" value="40000000"></constant>
	<!-- 設定檔案上傳時的臨時資料夾時F盤下的temp資料夾 -->
	<constant name="struts.multipart.saveDir" value="F:\\temp"></constant>

</struts>


<!-- struts-upload.xml檔案 -->
<struts>
    <package name="upload" namespace="/file" extends="struts-default">
    	<action name="upload" class="uploadAction">
    		<result name="success">/success.jsp</result>
    		<result name="error">/error.jsp</result>
    		<result name="input">/filetoolargeerror.jsp</result>
    		<param name="maximumSize">1000000</param>
    		<param name="allowedTypes">text/plain,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document</param>
    	</action>
    	
    	<action name="download" class="downloadAction">
    			<result name="success" type="stream">
    			<param name="inputName">fileInput</param>
    			<param name="contentDisposition">attachment;filename="${fileName}"</param>
    		</result>
    	</action>
    </package>
</struts>



接下來是applicationContext-bean.xml檔案,該檔案中通過對映將struts-upload.xml檔案中的action名稱與真實的javabean進行對映:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" >
	
	<!-- Spring管理Struts2的Action -->
	<bean name="uploadAction" class="com.yang.action.UploadAction" scope="prototype"></bean>
	
	<bean name="downloadAction" class="com.yang.action.DownloadAction" scope="prototype"></bean>
	
</beans>


具體處理檔案上傳和下載的Action,分別為UploadAction和DownloadAction:

package com.yang.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport { 
	
	private List<File> uploads;
	
	private List<String> uploadFileName;
	
	private List<String> uploadContentType;
	
	private long maximumSize;
	
	private String allowedTypes;

	public List<File> getUpload() {
		return uploads;
	}

	public void setUpload(List<File> uploads) {
		this.uploads = uploads;
	}

	public List<String> getUploadFileName() {
		return uploadFileName;
	}

	public void setUploadFileName(List<String> uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public List<String> getUploadContentType() {
		return uploadContentType;
	}

	public void setUploadContentType(List<String> uploadContentType) {
		this.uploadContentType = uploadContentType;
	}

	public long getMaximumSize() {
		return maximumSize;
	}

	public void setMaximumSize(long maximumSize) {
		this.maximumSize = maximumSize;
	}

	public String getAllowedTypes() {
		return allowedTypes;
	}

	public void setAllowedTypes(String allowedTypes) {
		this.allowedTypes = allowedTypes;
	}

	public String execute() throws Exception {
		//取得檔案上傳路徑(用於存放上傳的檔案)
		File uploadFile = new File(ServletActionContext.getServletContext().getRealPath("upload"));
		//判斷上述路徑是否存在,如果不存在則建立該路徑
		if (!uploadFile.exists()) {
			uploadFile.mkdir();
		}
		
		if(uploads != null){
			String[] allowedTypesStr = allowedTypes.split(",");
			//將允許的檔案型別列表放入List中
			List allowedTypesList = new ArrayList();
			for(int i = 0;i < allowedTypesStr.length; i++){
				allowedTypesList.add(allowedTypesStr[i]);
			}
			
			//判斷上傳檔案的型別是否是允許的型別之一
			for(int i = 0; i < uploads.size();i++){
				if(!allowedTypesList.contains(uploadContentType.get(i))){
					System.out.println("上傳檔案中包含非法檔案型別");
					ServletActionContext.getServletContext().setAttribute("errorMsg", "上傳檔案中包含非法檔案型別");
					return "error";
				}
			}
			
			//判斷檔案的大小
			for(int i = 0 ;i < uploads.size();i++){
				
				System.out.println(uploads.get(i).length());
				// 判斷檔案長度
				if (maximumSize < uploads.get(i).length()) {
					ServletActionContext.getServletContext().setAttribute("errorMsg", uploadFileName.get(i)+ "檔案過大");
					return "error";
				}
			}
			
			for(int i = 0; i < uploads.size();i++){
				// 第一種檔案上傳的讀寫方式
				FileInputStream input = new FileInputStream(uploads.get(i));
				FileOutputStream out = new FileOutputStream(uploadFile + "\\" + uploadFileName.get(i));
				
				try{
					byte[] b = new byte[1024];
					int m = 0;
					while ((m = input.read(b)) > 0) {
						out.write(b, 0, m);
					}
				}catch(Exception e){
					e.printStackTrace();
					ServletActionContext.getServletContext().setAttribute("errorMsg", uploadFileName.get(i) + "上傳過程中發生未知錯誤,請聯絡管理員。上傳失敗!");
					return "error";
				}finally{
					input.close();
					out.close();
					//刪除臨時檔案
					uploads.get(i).delete();
				}
			}
			return "success";
		}else{
			ServletActionContext.getServletContext().setAttribute("errorMsg", "請選擇上傳檔案");
			return "error";
		}
	}
}
package com.yang.action;

import java.io.InputStream;

import org.apache.struts2.ServletActionContext;

public class DownloadAction {

	private InputStream fileInput;
	
	private String fileName;
	
	public InputStream getFileInput() {
		return fileInput;
//		return ServletActionContext.getServletContext().getResourceAsStream("upload\\" + fileName);
	}

	public void setFileInput(InputStream fileInput) {
		this.fileInput = fileInput;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String execute() throws Exception {
		fileInput = ServletActionContext.getServletContext().getResourceAsStream("upload\\" + fileName);
		return "success";
	}
}


最後是前臺介面upload.jsp和download.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>upload</title>
</head>
<body>
	<form action="file/upload" method="post" enctype="multipart/form-data">
		<input type="file" name="upload">
		<input type="file" name="upload">
		<input type="file" name="upload">
		<input type="submit" name="btnUpload" value="上傳"> 
	</form>
</body>
</html>

<title>download</title>
</head>
<body>
	<a href="file/download?fileName=123.txt">123.txt</a>
</body>
</html>


以上內容為實現多檔案上傳以及問價下載的例項。在接下來的文章中將會介紹Spring與Hibernate整合的使用。