文件上传和下载(二)--【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




四、项目代码【点击这里下载


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值