Spring整合Struts2实现多文件上传及下载

来源:互联网 发布:网络信贷管理办法 编辑:程序博客网 时间:2024/05/22 05:19

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.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsdhttp://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集成的使用。