Struts2文件上传
  Struts2提供 FileUpload拦截器,用于解析 multipart/form-data 编码格式请求,解析上传文件的内容,fileUpload拦截器 默认在defaultStack栈中, 默认会执行的
  页面:<input type="file" name="upload" />
  在Action需要对上传文件内容进行接收 :

private File upload; // <input type="file" name="upload" />这里变量名 和 页面表单元素 name 属性一致
private String uploadContentType;//格式 :上传表单项name属性 + ContentType 、 上传表单项name属性 + FileName
private String uploadFileName;
public void setUpload(File upload) {//为三个对象 提供 setter 方法
  this.upload = upload;
}
public void setUploadContentType(String uploadContentType) {
  this.uploadContentType = uploadContentType;
}
public void setUploadFileName(String uploadFileName) {
  this.uploadFileName = uploadFileName;
}

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

FileUtils.copyFile(upload, new File("d:/upload",uploadFileName));

  关于struts2中文件上传细节:
    1.关于控制文件上传大小
      在default.properties文件中定义了文件上传大小:struts.multipart.maxSize=2097152 上传文件默认的总大小 2m 
    2.在struts2中默认使用的是commons-fileupload进行文件上传。
      # struts.multipart.parser=cos
      # struts.multipart.parser=pell
      struts.multipart.parser=jakarta (如果使用pell,cos进行文件上传,必须导入其jar包)        
    3.如果出现问题,需要配置input视图,在页面上可以通过<s:actionerror>展示错误信息.在页面上展示的信息,全是英文,要想展示中文,国际化
      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}
        {0}:<input type=“file” name=“uploadImage”>中name属性的值
        {1}:上传文件的真实名称
        {2}:上传文件保存到临时目录的名称
        {3}:上传文件的类型(对struts.messages.error.file.too.large是上传文件的大小)
    4.关于多文件上传时的每个上传文件大小控制以及上传文件类型控制.
      1.多文件上传
        只需要将action属性声明成List集合或数组就可以。

private List<File> upload;
private List<String> uploadContentType;
private List<String> uploadFileName;

      2.怎样控制每一个上传文件的大小以及上传文件的类型
        在fileupload拦截器中,通过其属性进行控制.
          maximumSize---每一个上传文件大小
          allowedTypes--允许上传文件的mimeType类型.
          allowedExtensions--允许上传文件的后缀名.

<interceptor-ref name="defaultStack">
  <param name="fileUpload.allowedExtensions">txt,mp3,doc</param>
</interceptor-ref>

  多文件上传案例:

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;
}
}

UploadAction

<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>

upload.jsp

<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="cn.itcast.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>

struts.xml

struts2中文件下载
  通过<result type="stream">完成  
    <result-type name="stream" class="org.apache.struts2.dispatcher.StreamResult"/>
  在StreamResult类中有三个属性:
    protected String contentType = "text/plain"; //用于设置下载文件的mimeType类型
    protected String contentDisposition = "inline";//用于设置进行下载操作以及下载文件的名称
    protected InputStream inputStream; //用于读取要下载的文件。
  要在action类中定义三个方法用于在XML文件中通过ognl获取值

// 设置下载文件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"); // 解决get请求中文名称乱码.
  FileInputStream fis = new FileInputStream("d:/upload/" + filename);
  return fis;
}

  要在配置文件中配置

<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>

  注:
    1:在struts2中进行下载时,如果使用<result type="stream">它有缺陷,例如:下载点击后,取消下载,服务器端会产生异常。
      在开发中的解决方案:可以下载一个struts2下载操作的插件,它解决了stream问题。
    2:处理浏览器之间不同的编码的getDownloadFileName方法

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; import sun.misc.BASE64Encoder; public class DownloadUtils { public static String getDownloadFileName(String agent, String filename) throws UnsupportedEncodingException {
if (agent.contains("MSIE")) {
// IE浏览器
filename = URLEncoder.encode(filename, "utf-8"); } else if (agent.contains("Firefox")) {
// 火狐浏览器
BASE64Encoder base64Encoder = new BASE64Encoder();
filename = "=?utf-8?B?"
+ base64Encoder.encode(filename.getBytes("utf-8")) + "?=";
} else {
// 其它浏览器
filename = URLEncoder.encode(filename, "utf-8");
} return filename;
}
}

DownloadUtils

  下载案例:

<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>

download.jsp

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException; import org.apache.struts2.ServletActionContext; import cn.itcast.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;
} }

DownloadAction

<action name="download" class="cn.itcast.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>

struts.xml

Struts2文件上传下载的更多相关文章

  1. JAVA Web 之 struts2文件上传下载演示(二)(转)

    JAVA Web 之 struts2文件上传下载演示(二) 一.文件上传演示 详细查看本人的另一篇博客 http://titanseason.iteye.com/blog/1489397 二.文件下载 ...

  2. JAVA Web 之 struts2文件上传下载演示(一)(转)

    JAVA Web 之 struts2文件上传下载演示(一) 一.文件上传演示 1.需要的jar包 大多数的jar包都是struts里面的,大家把jar包直接复制到WebContent/WEB-INF/ ...

  3. Struts2之文件上传下载

    本篇文章主要介绍如何利用struts2进行文件的上传及下载,同时给出我在编写同时所遇到的一些问题的解决方案. 文件上传 前端页面 <!-- 引入struts标签 --> <%@tag ...

  4. Struts2文件上传和下载(原理)

    转自:http://zhou568xiao.iteye.com/blog/220732 1.    文件上传的原理:表单元素的enctype属性指定的是表单数据的编码方式,该属性有3个值:1)     ...

  5. Struts2 文件上传,下载,删除

    本文介绍了: 1.基于表单的文件上传 2.Struts 2 的文件下载 3.Struts2.文件上传 4.使用FileInputStream FileOutputStream文件流来上传 5.使用Fi ...

  6. 【SSH2(实用文章)】--Struts2文件上传和下载的例子

    回想一下,再上一篇文章Struts2实现机制,该步骤做一步一步来解决,这种决心不仅要理清再次Struts2用法.映射机制及其在深入分析.最后一个例子来介绍Struts2一种用法,这里将做一个有关文件上 ...

  7. Struts2实现文件上传下载功能(批量上传)

    今天来发布一个使用Struts2上传下载的项目, struts2为文件上传下载提供了好的实现机制, 首先,可以先看一下我的项目截图 关于需要使用的jar包,需要用到commons-fileupload ...

  8. 学习Struts--Chap07:Struts2文件上传和下载

    1.struts2文件上传 1.1.struts2文件上传的基本概述 在开发web应用的时候,我们一般会为用户提供文件上传的功能,比如用户上传一张图像作为头像等.为了能上传文件,我们必须将表单的met ...

  9. struts2 文件上传和下载,以及部分源代码解析

    struts2 文件上传 和部分源代码解析,以及一般上传原理 (1) 单文件上传 一.简单介绍 Struts2并未提供自己的请求解析器,也就是就Struts2不会自己去处理multipart/form ...

随机推荐

  1. rsa加密解密

    2016年3月17日 17:21:08 星期四 现在越来越懒了.... 参考: http://www.xuebuyuan.com/1399981.html 左边是加密流程, 右边是解密流程 呃...有 ...

  2. SQL Update 巧用

    JOIN 样本 ********************************** Update 结存 set 结存.现有库存=c.入仓数-b.出仓数量 from 结存 a )) 入仓数 from ...

  3. How can I fix “Compilation unit name must end with .java, or one of the registered Java-like extensions”?

    How can I fix “Compilation unit name must end with .java, or one of the registered Java-like extensi ...

  4. IOS-01零碎知识总结

    1. 变量的@public @private @package @protected 声明有什么含义? @public  可以被所有的类访问 @private  只有该类的方法可以访问,子类的都不能访 ...

  5. 9.12/ css3拓展、js基础语法、程序基本知识、数据类型、运算符表达方式、语句知识点

    css3拓展: <display:none>  将某个元素隐藏       <visibility:hidden>  也是将某个元素隐藏 <display:block&g ...

  6. PHP工厂模式的研究

    工厂方法模式 把 创造者类 和要生产的 产品类 分离.创建者是一个工厂类,其定义了产品生产的类方法.一般情况下,创建者类的每个子类实例化一个相应的产品子类. 下面是单个产品的实现代码: <?ph ...

  7. 启动Eclipse弹出:Failed to load JavaHL Library 错误框的解决办法

    一.问题背景描述: eclipse安装完svn插件以后,在启动时出现:Failed to load JavaHL Library.  These are the errors that were en ...

  8. August 9th 2016, Week 33rd Tuesday

    Tomorrow is never clear, our time is here. 明天是未知的,我们还是要过好当下. Tomorrow is not unpredictable, it is cl ...

  9. Javascript异步编程方法总结

    现在我们有三个函数,f1, f2, f3 按正常的思路我们会这样写代码: function f1 (){}; function f2 (){}; function f3 (){}; //在这里调用函数 ...

  10. 读取Spring的配置文件applicationContext.xml的5种方法

    1.利用ClassPathXmlApplicationContext,这种方式配置文件应该放在类包同路径下Java代码: ApplicationContext ct=new ClassPathXmlA ...