Struts实现上传、下载

HTML
HTML页面需要做两件事情,首先,表单需要指定enctype = "multipart/form-data",其次需要一个类型为file的<input>表单控件。 
<form name="myForm" method="post"action="/mywebapp/uploadMyFile.do" enctype="multipart/form-data">
       Select File: <input type="file" name="myFile">
         <input type="submit" value="Upload File">
</form>
JSP
上面的HTML标签用Struts标签代替就是以下代码: 
<html:form action="/uploadMyFile.do" enctype="multipart/form-data">
Select File: <html:file property="myFile">
<html:submit value="Upload File"/>
</html:form>
ActionForm
这个ActionForm需要一个FormFile类型的字段。 
一般的ActionForm
       private FormFile myFile;
动态ActionForms
在struts-config.xml文件中写上: 
   <form-bean name="myForm" type="org.apache.struts.action.DynaActionForm">
       <form-property name="myFile" type="org.apache.struts.upload.FormFile"/>
   </form-bean>
在Action中需要怎么写呢?
其实没什么特殊的,就象和得到其他属性一样,从ActionForm中得到FormFile属性,得到后可以随意进行处理。比如我们可以从FileForm中得到文件名,文件大小,文件内容 
 ...
  UploadForm uf = (UploadForm) form;
  String description = uf.getDescription();
  FormFile file = uf.getUploadFile();
  System.out.println("description=" + description);
  String filePath =
   getServlet().getServletContext().getRealPath("/");

  FileOutputStream out =
   new FileOutputStream(filePath + file.getFileName());
  InputStream in = file.getInputStream();
  byte[] readBytes = new byte[4096];
  int read = -1;
  while((read = in.read(readBytes, 0, 4096)) != -1) {
   out.write(readBytes, 0, read);
  }
  in.close();
  out.close();
......

文件上传的配置
在struts-config.xml的<controller>element中可以设置如下参数来配置文件上传: 
bufferSize - 处理文件上传的缓冲区大小,单位是字节。默认是4096byte。 
maxFileSize - 允许上传文件的大小。可以使用K,M,G为单位。默认是250M。 
multipartClass - muiltpart请求处理器类的全局标识名。默认是org.apache.struts.upload.CommonsMultipartRequestHandler 
tempDir - 处理文件上传的临时目录。还有一种可选的文件上传插件的方式可提供使用,那就是实现org.apache.struts.upload.MultipartRequestHandler接口。可以在struts-config.xml的<controller>的multipartClass来指定这个实现给接口的类。
StrutsFileDownload
Struts 1.2.6中推出了新的DownloadAction,用来简化下载操作。
实现DownloadAction我们需要扩展org.apache.struts.actions.DownloadAction并实现getStreamInfo()方法。如果我们要更改默认的缓冲大小,我们也可以覆盖getBufferSize()方法。  
实现getStreamInfo() 方法getStreamInfo() 方法返回一个StreamInfo对象- 它是DownloadAction类的内部类,其实是个内部接口。DownloadAction为这个接口提供了两个具体的静态内部实现类: 
FileStreamInfo - 简化从磁盘系统下载文件。需要连同content type传入一个java.io.File对象到构造方法中。 
ResourceStreamInfo - 简化从web应用资源下载文件。需要传入ServletContext,路径以及content type 到它的构造方法中。 
在下面的例子中,我们还提供了一个以Byte array方法实现StreamInfo接口的代
码。 
实现getBufferSize() 方法
DownloadAction默认返回4096byte的缓冲区我们可以覆盖这个方法来自定义用
来传输文件的缓冲区大小 
范例
下面有三个例子: 
使用文件
使用web应用资源
使用byte array 
FileStreamInfo范例
DownloadAction使用文件的例子。这个范例从struts-config.xml的action
mapping的parameter属性来得到文件名。 
......
    protected StreamInfo getStreamInfo(ActionMapping mapping, 
                                       ActionForm form,
                                       HttpServletRequest request, 
                                       HttpServletResponse response)
            throws Exception {
        // Download a "pdf" file - gets the file name from the
        // Action Mapping's parameter
        String contentType = "application/pdf";
        File file = new File(mapping.getParameter());
        return new FileStreamInfo(contentType, file);
   }
}
ResourceStreamInfo范例
DownloadAction使用web应用资源的范例。这个范例从struts-config.xml的
action mapping的parameter属性来得到web应用资源的路径。 
...
    protected StreamInfo getStreamInfo(ActionMapping mapping, 
                                       ActionForm form,
                                       HttpServletRequest request, 
                                       HttpServletResponse response)
            throws Exception {
        // Download a "jpeg" file - gets the file name from the
        // Action Mapping's parameter
        String contentType         = "image/jpeg";
        String path                = mapping.getParameter();
        ServletContext application = servlet.getServletContext();
        return new ResourceStreamInfo(contentType, application, path);
    }
Byte Array 范例
DownloadAction使用字节数组(byte array)的范例。 
这个例子创建了一个实现了StreamInfo接口的ByteArrayStreamInfo内部类。

    protected StreamInfo getStreamInfo(ActionMapping mapping, 
                                       ActionForm form,
                                       HttpServletRequest request, 
                                       HttpServletResponse response)
            throws Exception {
        // Download a "pdf" file
        String contentType = "application/pdf";
        byte[] myPdfBytes  = null;// Get the bytes from somewhere
        return new ByteArrayStreamInfo(contentType, myPdfBytes);
    }
    protected class ByteArrayStreamInfo implements StreamInfo {
        
        protected String contentType;
        protected byte[] bytes;
        
        public ByteArrayStreamInfo(String contentType, byte[] bytes) {
            this.contentType = contentType;
            this.bytes = bytes;
        }
         public String getContentType() {
            return contentType;
        }
        public InputStream getInputStream() throws IOException {
            return new ByteArrayInputStream(bytes);
        }
    }
}
在WEB页面上使用DownloadAction
最大的疑惑是我么如何使用这个Action? 
需要做两件事情: 
和任何Struts的action一样,需要在struts-config.xml中进行配置。 
在WEB页面中使用它对文件进行连接 
下面是struts-config.xml配置的一个例子: 
    <action path="/downloadMyPdfFile" type="myPackage.ExampleFileDownload"      parameter="/foo/bar.pdf">
    <action path="/downloadMyImage"   type="myPackage.ExampleResourceDownload"      parameter="/images/myImage.jpeg">
那么在我们的JSP页面,可以使用类似下面的例子: 
    <html:link action="/downloadMyPdfFile">Click Here to See the PDF</html:link>
注意:我们可能要将struts配置文件中<controller>属性的nocache值设置为false。如果设置为true,可能在IE上不能成功下载文件,但是在Firefox和Safari上工作正常。  <controller contentType="text/html;charset=UTF-8" locale="true" nocache="false" />
内容部署(Content Disposition)
设置Content Disposition
DownloadAction不能处理content dispositon头部。最简单的方法是在getStreamInfo()方法中设置,比如: 
.....
        // File Name
        String fileName = mapping.getParameter();
        // Set the content disposition
        response.setHeader("Content-disposition", 
                           "attachment; filename=" + fileName);
         // Download a "pdf" file - gets the file name from the
        // Action Mapping's parameter
        String contentType = "application/pdf";
        File file  = new File(fileName);
        return new FileStreamInfo(contentType, file);
        
    }
如果需要文件名做为参数,可能需要首先把文件前面的任何路径信息先清除。
Content Disposition的值
我们可以设置content disposition来下载一个文件或者在浏览器中打开一个文件。 
在浏览器中打开文件的例子写法: "inline; filename=myFile.pdf" 
下载的例子写法: "attachment; filename=myFile.pdf" 
显示图片的话,可以使用content disposition的"inline"选项。
-----------------------------------------------------------------------
看了我试着做了一个,感觉提供的DownloadAction还是很简单的。
jsp:
<html:form action="/uploadAction.do?action=upload" enctype = "multipart/form-data">
<p><html:link action="/uploadAction.do">下载</html:link></p>
<p>描述:<html:text property="description"/></p>
<p>文件:<html:file property="uploadFile"/></p>
<p><input type="submit" value="上传"/></p>
</html:form>
action:
 protected StreamInfo getStreamInfo(ActionMapping mapping,
   ActionForm form,
   HttpServletRequest request,
   HttpServletResponse response) throws Exception {
  String contentType = "application/pdf";
  File file = getFile();
  response.setHeader("Content-disposition",
                "attachment; filename=" + file.getName());
//  response.setHeader("Content-disposition",
//                "inline; filename=" + file.getName());
  return new FileStreamInfo(contentType, getFile());
 }
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值