`
SIHAIloveYAN
  • 浏览: 113303 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类

struts2教程(8)--文件上传下载

 
阅读更多

Struts2文件上传下载

一、Struts2文件上传

提供 FileUpload 拦截器,用于解析 multipart/form-data 编码格式请求,解析上传文件的内容

fileUpload拦截器 默认在 defaultStack 栈中, 默认会执行的

Action需要对上传文件内容进行接收

页面

<input type="file" name="upload" />


Action

	public class UploadAction extends ActionSupport {

// 接收上传内容

// <input type="file" name="upload" />

private File upload; // 这里变量名 和 页面表单元素 name 属性一致

private String uploadContentType;

private String uploadFileName;

} 

注意:

格式 : 上传表单项name属性 + ContentType 、 上传表单项name属性 + FileName

为三个对象 提供 setter 方法

通过FileUtils 提供 copyFile 进行文件复制,将上传文件 保存到服务器端


二、Struts2文件上传问题解决

1、配置 input 视图 ,作为上传出错后 跳转页面

在文件上传时,如果发生错误 fileUpload拦截器 会设置错误信息,workflow拦截器 跳转到 input 视图

2、struts.multipart.parser=jakarta 定义文件上传,采用 commons-fileupload 技术

同时支持 cos pell 上传技术 (如果使用其它上传技术,单独下载jar包 )

3、通过 struts.multipart.maxSize 常量设置文件上传总大小限制

struts.multipart.maxSize=2097152 默认上传文件总大小 2MB

超过文件总大小,跳转input 视图, 通过 <s:actionError /> 回显错误信息


4、在struts.xml 设置上传总大小

<constant name="struts.multipart.maxSize" value="20000000"></constant>


5、设置上传文件总大小,对所有上传form有效,只想对当前form进行设置,可以设置fileUpload拦截器属性

FileUpload 拦截器有 3 个属性可以设置.

* maximumSize: 上传文件的最大长度(以字节为单位), 默认值为 2 MB

* allowedTypes: 允许上传文件的类型, 各类型之间以逗号分隔

* allowedExtensions: 允许上传文件扩展名, 各扩展名之间以逗号分隔

如果针对fileUpload 进行参数设置,当出错时,在页面通过 <s:fieldError /> 回显错误信息

struts-messages.properties 文件里预定义 上传错误信息,通过覆盖对应key 显示中文信息

struts.messages.error.uploading=Error uploading: {0}

struts.messages.error.file.too.large=The file is to large to be uploaded: {0} "{1}" "{2}" {3}

struts.messages.error.content.type.not.allowed=Content-Type not allowed: {0} "{1}" "{2}" {3}

struts.messages.error.file.extension.not.allowed=File extension not allowed: {0} "{1}" "{2}" {3}

修改为

struts.messages.error.uploading=上传错误: {0}

struts.messages.error.file.too.large=上传文件太大: {0} "{1}" "{2}" {3}

struts.messages.error.content.type.not.allowed=上传文件的类型不允许: {0} "{1}" "{2}" {3}

struts.messages.error.file.extension.not.allowed=上传文件的后缀名不允许: {0} "{1}" "{2}" {3}


上传案例:

jsp页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    
    <title>My JSP 'index.jsp' starting page</title>
	
  </head>
  
  <body>
  	<s:fielderror/>
  	<s:actionerror/>
  	<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
  		<input type="file" name="upload"><br>
  		<input type="file" name="upload"><br>
  		<input type="file" name="upload"><br>
  		<input type="submit" value="上传">
  	</form>
  </body>
</html>

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.custom.i18n.resources" value="message"></constant>
	<constant name="struts.multipart.maxSize" value="20971520"></constant>
	<package name="default" namespace="/" extends="struts-default">


		<action name="upload" class="com.sihai.action.UploadAction">
			<result name="input">/upload.jsp</result>
			<interceptor-ref name="defaultStack">
				<param name="maximumSize">2097152</param>
				<param name="fileUpload.allowedExtensions">txt,mp3,doc</param>
			</interceptor-ref>
		</action>

	</package>
</struts>

action:

package com.sihai.action;

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

import org.apache.commons.io.FileUtils;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {

	// 在action类中需要声明三个属性
	private List<File> upload;
	private List<String> uploadContentType;
	private List<String> uploadFileName;

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

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

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

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

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

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

	@Override
	public String execute() throws Exception {

		for (int i = 0; i < upload.size(); i++) {
			
			
			System.out.println("上传文件的类型:" + uploadContentType.get(i));
			System.out.println("上传文件的名称:" + uploadFileName.get(i));

			// 完成文件上传.
			FileUtils.copyFile(upload.get(i), new File("d:/upload", uploadFileName.get(i)));
		}
		return null;
	}

}


三、多文件上传

第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jarcommons-io-1.3.2.jar。这两个文件可以从http://commons.apache.org/下载。

第二步:把form表的enctype设置为:“multipart/form-data“,如下:

<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/xxx.action" method="post">

  <input  type="file" name="uploadImages">

  <input  type="file" name="uploadImages">

</form>


第三步:在Action类中添加以下属性,属性红色部分对应于表单中文件字段的名称:

public class uploadAction{

  private File[] uploadImages;//得到上传的文件

  private String[] uploadImagesContentType;//得到文件的类型

  private String[] uploadImagesFileName;//得到文件的名称

  //这里略省了属性的getter/setter方法

  public String saveFiles() throws Exception{

        ServletContext sc = ServletActionContext.getServletContext();

        String realpath = sc.getRealPath("/uploadfile");

        try {

            if(uploadImages!=null&&uploadImages.length>0){

                 for(int i=0;i<uploadImages.length;i++){

                         File destFile = new File(realpath,uploadImageFileNames[i]);

                         FileUtils.copyFile(uploadImages[i], destFile);

                  }

             }

         } catch (IOException e) {

              e.printStackTrace();}return "success";}}

 


四、Struts2文件下载

1struts2 完成文件下载,通过 结果集类型 (Result Typestream 来完成的

struts-default.xml 定义 <result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>


2) 使用Stream结果集 完成文件下载

文件下载原理: 服务器读取下载文件内容,通过Response响应流写回, 设置 ContentTypeContentDisposition 头信息

public class StreamResult extends StrutsResultSupport {

protected String contentType = "text/plain"; // contentType头信息  (下载文件对应 MIME协议规定类型 )

protected String contentDisposition = "inline"; // ContentDisposition头信息 (下载文件打开方式 inline浏览器内部打开, attachment 以附件形式打开)

protected String inputName = "inputStream";  // 需要Action中 提供 getInputStream 方法 返回 InputStream 提供下载文件 内容

} 


3)Action 提供 InputStream 返回值 getInputStream 方法 ------- 指定下载文件流

配置 stream 结果集 参数 <param name="contentType">${contentType}</param> ---- Action 中提供 getContentType


ServletActionContext.getServletContext().getMimeType(filename);

配置 stream 结果集 参数 <param name="contentDisposition">attachment;filename=${filename}</param> ---- Action 提供 getFilename


下载附件名乱码问题

	public String encodeDownloadFilename(String filename, String agent)

throws IOException {

if (agent.contains("Firefox")) { // 火狐浏览器

filename = "=?UTF-8?B?"

+ new BASE64Encoder().encode(filename.getBytes("utf-8"))

+ "?=";

} else { // IE及其他浏览器

filename = URLEncoder.encode(filename, "utf-8");

}

return filename;

}


文件下载案例

jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>My JSP 'index.jsp' starting page</title>

</head>

<body>
	<a href="${pageContext.request.contextPath}/download?filename=a.txt">a.txt</a>
	<br>
	<a href="${pageContext.request.contextPath}/download?filename=捕获.png">捕获.png</a>
	<br>
</body>
</html>

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.custom.i18n.resources" value="message"></constant>
	<constant name="struts.multipart.maxSize" value="20971520"></constant>
	<package name="default" namespace="/" extends="struts-default">
		<action name="download" class="com.sihai.action.DownloadAction">
			<result type="stream">
				<param name="contentType">${contentType}</param> <!-- 调用当前action中的getContentType()方法 -->
				<param name="contentDisposition">attachment;filename=${downloadFileName}</param>
				<param name="inputStream">${inputStream}</param><!-- 调用当前action中的getInputStream()方法 -->
			</result>
		</action>
	</package>
</struts>

package com.sihai.action;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import org.apache.struts2.ServletActionContext;

import com.sihai.utils.DownloadUtils;

import com.opensymphony.xwork2.ActionSupport;

public class DownloadAction extends ActionSupport {

	private String filename; // 要下载文件的名称

	public String getFilename() {
		return filename;
	}

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

	// 设置下载文件mimeType类型
	public String getContentType() {

		String mimeType = ServletActionContext.getServletContext().getMimeType(
				filename);
		return mimeType;
	}

	// 获取下载文件名称
	public String getDownloadFileName() throws UnsupportedEncodingException {

		return DownloadUtils.getDownloadFileName(ServletActionContext
				.getRequest().getHeader("user-agent"), filename);

	}

	public InputStream getInputStream() throws FileNotFoundException,
			UnsupportedEncodingException {

		filename = new String(filename.getBytes("iso8859-1"), "utf-8"); // 解决中文名称乱码.

		FileInputStream fis = new FileInputStream("d:/upload/" + filename);
		return fis;
	}

	@Override
	public String execute() throws Exception {
		System.out.println("进行下载....");
		return SUCCESS;
	}

}



分享到:
评论

相关推荐

    Struts2-2.3.16 全jar包

    commons-fileupload-1.2.1.jar//文件上传时用的,为了以后用到,最好加入 commons-io-1.3.2.jar//同上 commons-logging-1.0.4.jar freemarker-2.3.16.jar javassist-3.7.ga.jar ognl-3.0.jar struts2-core-2.2.1.1....

    Struts2技术手册-Struts2精华教程-电子书

    本书内容非常全面,涵盖了众多书籍所有知识要点,并结合作者自己经验总结而编写,内容相当丰富,是查找技术的...文件上传 .....文件下载 .....插件_JSON .....插件_DOJO .....插件_convention .....插件_config-browser

    Struts2文件上传和下载教程

    Struts2文件上传和下载教程

    struts2 文件上传 教程

    struts2文件上传-基本

    struts2文件上传教程

    struts2文件上传教程

    Struts2入门教程(全新完整版)

    九、文件上传下载(了解) 55 1. 上传实例 55 2.下载实例 57 十、类型转换 57 1.基于Action的直接属性转换 57 2.基于Action的间接属性vo转换 59 十一、注解配置 59 十二、总结 本教程对struts2的基本知识进行了一些...

    struts2学习教程

    struts2学习教程包括:第一个Struts2程序,处理一个form多个submit,struts.xml常用配置解析,使用validate方法验证数据,使用Validation框架验证数据,在Action类中获得HttpServletResponse对象的四种方法,上传...

    个人认为目前最完备的Struts2教程

    01 为Struts 2.0做好准备 02 常用的Struts 2.0的标志(Tag) 03 Struts 2.0的Action...09 在Struts 2中实现文件上传 10 在Struts 2中实现CRUD 11 Struts 2中的OGNL 12 Struts 2的新表单标志的使用 13 Struts 2与AJAX

    浪曦Struts2系列视频教程

    教程名称:浪曦Struts2系列视频教程课程目录:【】1 Struts2入门与配置【】10 Struts2的核心 拦截器【】11 Struts2的核心 拦截器续【】12 Struts2的文件上传和下载【】13 Struts2的文件上传和下载续【】14 Struts2的...

    struts2入门教程

    很好的struts2入门教程,网上搜集整理的! 内容: ... ·Struts 2中实现文件上传 ·Struts 2中的OGNL ·Strus 2的新表单标签的使用 ·Struts 2与AJAX ·Struts2分页 ·完全Struts's Tiles入门

    struts2教程ppt

    struts2教程,一共有八个ppt。内容丰富。有:1、struts2配置与运行。2、类型转换器。3、 数据较验。4、拦截器。5、文件上传与下载。6、struts2国际化。7、 标签介绍。8、Struts2的插件。

    文件上传struts2相关经典教程

    struts2相关经典教程 fileupload struts2

    struts2的文件上传

    struts2的文件上传教程,讲的挺好的,值得下载

    struts2.0中文教程

    01 为Struts 2.0做好准备 02 常用的Struts 2.0的标志(Tag) 03 Struts 2.0的Action讲解...09 在Struts 2中实现文件上传 10 在Struts 2中实现CRUD 11 Struts 2中的OGNL 12 trus 2的新表单标志的使用 13 Struts 2与AJAX

    Struts1.x的上传文件示例

    Struts1.x的上传文件示例。Struts1.x的教程参考我的Blog:http://blog.csdn.net/boyazuo

    struts构建文件上传教程

    struts构建文件上传,如果有这方面需求的朋友,希望能给你一点帮助.

    Struts2中文教程

    Struts2中文教程,包括:标志,Action讲解,国际化,拦截器,文件上传等等,内容非常详细!

    struts2简单教程

    itcast的struts2简单教程 包括:环境搭建、国际化、OGNL、标签、拦截器、文件上传等

Global site tag (gtag.js) - Google Analytics