struts2.0上传下载

strtus2.0实现上传
实现原理
Struts 2是通过Commons FileUpload文件上传。
1.Commons FileUpload通过将HTTP的数据保存到临时文件夹,
2.然后Struts使用fileUpload拦截器将文件绑定到Action的实例中。从而我们就能够以本地文件方式的操作浏览器上传的文件。
 
以下是例子所依赖类包的列表:
struts2.0上传下载_第1张图片 
 
(1)
上传的JSP页面:FileUpload.jsp:
<%@ page contentType="text/html;charset=GBK" language="java"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title> Struts 2文件上传示例 </title>
</head>
<body>
    <s:form action="fileUpload" method="post" enctype="multipart/form-data">
        <s:file name="loadFile" label="图片文件"/>
        <s:textfield name="caption" label="描述"/>       
        <s:submit/>
    </s:form>
</body>
</html>
注意:
1.enctype须设置为"multipart/form-data";
2.<s:file name="loadFile">标签将上传文件赋值给ACTION中的File loadFile属性。
(2)
实现上传的ACTION--FileUploadAction.java
此ACTION实现功能:将浏览器上传的文件复制到web应用程序根根目录下的uploadImages目录下。
public class FileUploadAction extends ActionSupport {
 private static final long serialVersionUID = 1L;
 private static final int BUFFER_SIZE = 16 * 1024;
 /*
  * 一个loadFile,
  * 不但须设置setLoadFile(),
  * 还需要设置setLoadFileContentType(String contentType):获取上传文件的MIME类型
  *         setLoadFileFileName(String fileName):上传文件的文件名,此文件名不包括文件路径
  * 因此:
  * <s:file name="xxx">,则ACTION中要有三个对应的setter方法:
  * setxxx(),  
  * setxxxContentType(String contentType)
  * setxxxFileName(String fileName)   
  * */
 private File loadFile;
 private String contentType;
 private String fileName;
 //用于showUpload.jsp获取
 private String imageFileName;
 private String caption;
 public void setLoadFileContentType(String contentType) {
  this.contentType = contentType;
 }
 public void setLoadFileFileName(String fileName) {
  this.fileName = fileName;
 }
 public void setLoadFile(File loadFile) {
  this.loadFile =loadFile;
 }
 public String getImageFileName() {
  return imageFileName;
 }
 public String getCaption() {
  return caption;
 }
 public void setCaption(String caption) {
  this.caption = caption;
 }
 private static void copy(File src, File dst) {
  try {
   InputStream in = null;
   OutputStream out = null;
   try {
    in = new BufferedInputStream(new FileInputStream(src),
      BUFFER_SIZE);
    out = new BufferedOutputStream(new FileOutputStream(dst),
      BUFFER_SIZE);
    byte[] buffer = new byte[BUFFER_SIZE];
    while (in.read(buffer) > 0) {
     out.write(buffer);
    }
   } finally {
    if (null != in) {
     in.close();
    }
    if (null != out) {
     out.close();
    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 @Override
 public String execute() {
  imageFileName = fileName;
  File dir=new File(ServletActionContext.getServletContext()
    .getRealPath("/UploadImages "));
  File imageFile = new File(ServletActionContext.getServletContext()
    .getRealPath("/UploadImages")+File.separator+ imageFileName);
  if(!dir.exists()) dir.mkdirs();
  System.out.println(ServletActionContext.getServletContext()
    .getRealPath("/UploadImages")+File.separator+ imageFileName);
  copy(loadFile, imageFile);
  return SUCCESS;
 }
}
(3)
struts.xml中相应配置:
因为struts是使用fileUpload拦截器来实现文件的上传的,所以在配置时,须调用fileUpload拦截器。
1.
 <package name="fileUploads" extends="struts-default">
  <action name="fileUpload" class="com.struts2.app.FileUploadAction">
   <interceptor-ref name="fileUploadStack" />
   <result name="input">/FileUpload.jsp</result>
   <result name="success">/ShowUpload.jsp</result>
  </action>
 </package>
2.
若上限制用户上传图片的类型,可以为拦截器添加参数allowedTypes,且在ACTION中添加相应的属性定义。(此设置为本文应用的设置)
 <package name="fileUploads" extends="struts-default">
  <action name="fileUpload"
   class="com.struts2.app.FileUploadAction">
   <interceptor-ref name="fileUpload">
    <param name="allowedTypes">
     image/bmp,image/png,image/gif,image/jpg,image/jpeg
    </param>
                                <!-- 配置允许上传的文件大小,单位字节 -->
                                <param name="maximumSize">102400</param>
   </interceptor-ref>
   <interceptor-ref name="defaultStack" />
   <result name="input">/FileUpload.jsp</result>
   <result name="success">/ShowUpload.jsp</result>
  </action>
 </package>
(4)
strtus.multipart.saveDir用于指定存放临时文件的文件夹。
如:strtus.multipart.saveDir=/tmp,则上传的文件就会临时保存到根目录下的tmp文件夹中。
(5)
添加显示上传图片的JSP页面:
<%@ page contentType="text/html;charset=GBK" language="java"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
   <title> Struts 2文件上传示例 </title>
</head>
<body>
    <div style ="padding: 4px; text-align: center">
        <img src ='UploadImages/<s:property value ="imageFileName"/> '/>
        <br/>
        <s:property value ="caption"/>
    </div>
</body>
</html>
(6)
实现多文件上传:
6.1
与单文件上传相似,Struts 2实现多文件上传也很简单。你可以将多个<s:file />绑定Action的数组或列表。如下例所示:
< s:form action ="doMultipleUploadUsingList" method ="POST" enctype ="multipart/form-data" >
    < s:file label ="File (1)" name ="uploads" />
    < s:file label ="File (2)" name ="uploads" />
    < s:file label ="FIle (3)" name ="uploads" />
    < s:submit />
</ s:form >
6.2
如果你希望绑定到数组,Action的代码应类似:
    private File[] uploads;
    private String[] uploadFileNames;
    private String[] uploadContentTypes;
    public File[] getUpload() { return this .uploads; }
    public void setUpload(File[] uploads) { this .uploads = uploads; }
    public String[] getUploadFileName() { return this .uploadFileNames; }
    public void setUploadFileName(String[] uploadFileNames) { this .uploadFileNames = uploadFileNames; }
    public String[] getUploadContentType() { return this .uploadContentTypes; }
    public void setUploadContentType(String[] uploadContentTypes) { this .uploadContentTypes = uploadContentTypes; }
如果你想绑定到列表,则应类似:
private List < File > uploads = new ArrayList < File > ();
    private List < String > uploadFileNames = new ArrayList < String > ();
    private List < String > uploadContentTypes = new ArrayList < String > ();
    public List < File > getUpload() {
        return this .uploads;
   }
    public void setUpload(List < File > uploads) {
        this .uploads = uploads;
   }
    public List < String > getUploadFileName() {
        return this .uploadFileNames;
   }
    public void setUploadFileName(List < String > uploadFileNames) {
        this .uploadFileNames = uploadFileNames;
   }
    public List < String > getUploadContentType() {
        return this .uploadContentTypes;
   }
    public void setUploadContentType(List < String > contentTypes) {
        this .uploadContentTypes = contentTypes;
   }
(7)
与上传相关的还有:
strut2.0上传文件进度条等相关内容。可google一下.
strtus2.0实现下载
(1)
先来看下 Servlet 如何实现文件下载的,直接见代码:
PrintWriter out = response.getWriter();

//不管实际类型,待下载文件 ContentType 统一指定为 application/octet-stream
response.setContentType( "application/octet-stream");

//中文文件名必须转码为 ISO8859-1,否则为乱码
String fileName = new String( "文本文件.txt".getBytes(), "ISO8859-1");

//作为附件下载,相应的 "inline;filename = "+fileName 是在线(浏览器中显示内容)打开
response.setHeader( "Content-Disposition", "attachment;filename=" + fileName);

//因为文件编码也为 ISO8859-1,所以内容须转码成 ISO8859-1,尚不知如何控制下载文本文件的编码
//或有谁知道的,还请告诉我一下。 文件内容可以从物理文件中来,或者数据库中读取填入等等
out.write( new String( "Servlet 文件下载测试".getBytes(), "ISO8859-1"));

out.close();
知道了上面各行的含义,再来看下 Struts2 的解决方式,其实不过是把某些代码的功能移入到了配置文件而已。在李刚所著的《Struts 2 权威指南》中说 Struts 实现文件下载是由一个 download 拦截器。其实不然,只是一个 StreamResult(org.apache.struts2.dispatcher.StreamResult) 而已,也不像实现文件上传那样要额外的 JAR 包。
在 StreamResult 中有以下几个默认属性要留意一下:
    public static final String DEFAULT_PARAM = "inputName";
    protected String contentType = "text/plain";
    protected String contentDisposition = "inline";
    protected String inputName = "inputStream";
    protected InputStream inputStream;
    protected int bufferSize = 1024;
StreamResult 的实现细节敬请阅读它的源代码,实现过程一言以蔽之就是:从 inputStream 获取内容,以相应的 contentType、contentDisposition 和 bufferSize 输出给浏览器,对 contentType 和 contentDisposition 的相应设置就能实现文件下载,可对照前面 Servlet 的实现。看个实际的例子吧。
struts.xml 中 Action 的配置,假定 Action 类为 com.unmi.DownLoadAction
<action name= "download" class= "com.unmi.action.DownloadAction">
  <result name= "success" type= "stream"><!--type 为 stream 应用 StreamResult 处理-->
         <param name= "contentType">application/octet-stream</param><!--默认为 text/plain-->
            
         <!-- 默认就是 inputStream,它将会指示 StreamResult 通过 inputName 属性值的 getter 方法,比如这里就是 getInputStream() 来获取下载文件的内容,意味着你的 Action 要有这个方法 -->
         <param name= "inputName">inputStream</param>
            
         <!-- 默认为 inline(在线打开),设置为 attachment 将会告诉浏览器下载该文件,filename 指定下载文件保有存时的文件名,若未指定将会是以浏览的页面名作为文件名,如以 download.action 作为文件名,这里使用的是动态文件名,${fileName}, 它将通过 Action 的 getFileName() 获得文件名 -->
         <param name= "contentDisposition">attachment;filename= "${fileName}"</param>
         <param name= "bufferSize">4096</param><!-- 输出时缓冲区的大小 -->
  </result>
说明:对于上面的配置其他参数可以用默认值,关键就是 contentDisposition 要设置为 attachment 才能提示下载,同时用 filename 指定文件名,若直接指定非动态的文件名。
DownloadAction 代码,需要实现 getInputStream() 返回输入流;因前面用的动态文件名,所以须加上 getFileName() 返回文件名,若非动态文件名,则该方法可省去。
package com.unmi.action;

import java.io.*;
import java.text.*;
import java.util.Date;

/**
* 文件下载的 Action    
* @author Unmi
*/
public class NetbookSerialAction {

   public String execute() throws Exception {
     //这里可加入权限控制
     return "success";
  }

   //获得下载文件的内容,可以直接读入一个物理文件或从数据库中获取内容
   public InputStream getInputStream() throws Exception {
     //return new FileInputStream("somefile.rar"); 直接下载 somefile.rar

     //和 Servlet 中不一样,这里我们不需对输出的中文转码为 ISO8859-1
     return new ByteArrayInputStream( "Struts2 文件下载测试".getBytes());
  }

   //对于配置中的 ${fileName}, 获得下载保存时的文件名
   public String getFileName() {
    DateFormat df = new SimpleDateFormat( "yyyy-MM-dd");
    String fileName = "序列号(" + df.format( new Date()) + ").txt";
     try {
       //中文文件名也是需要转码为 ISO8859-1,否则乱码
       return new String(fileName.getBytes(), "ISO8859-1");
    } catch (UnsupportedEncodingException e) {
       return "impossible.txt";
    }
  }
}
谨记一个就是,要想下载的文件名不乱码就要以 ISO8859-1 字符集进行转码,内容会否乱码可在调试中解决。
好啦,启动服务,访问 http://localhost:8080/teststruts2/download.action,浏览器便会提示下载 序列号(2009-06-17).txt,内容为:“Struts2 文件下载测试”。
 

你可能感兴趣的:(struts,职场,休闲)