struts2实现简单的文件上载功能(支持多类型上载)

struts2实现简单的文件下载功能(支持多类型下载)
本文出自:http://hi.baidu.com/dinguangx/blog/item/17fcf3f330f01a56342acc1f.html


文件下载相对于文件上传要简单得多,最简单的方式就是直接在页面上给出一个下载文件的链接,使用Struts 2框架来控制文件的下载,关键是需要配置一个stream类型的结果,需要指定下面4个属性。

contentType属性:指定被下载文件的文件类型,默认为text/plain。

inputName属性:指定被下载文件的入口输入流。

contentDisposition属性:指定下文件的文件名称。

bufferSize属性:指定下载文件时的缓冲区大小,默认的是1024字节。

配置上面4个属性,既可以在配置文件中配置,也可以在Action中设置该属性来完成配置。

假设现在要下载的是web应用下的upload目录下的test.doc

其中进行处理的Action清单(DownloadAction.java)如下:

public class DownloadAction extends ActionSupport {

private String fileName = "test.doc";

public void setFileName(String fileName){
   this.fileName = fileName;
}

public String getFileName(){
   return this.fileName;
}

public InputStream getDownloadFile() {
   System.out.println(fileName);
 
   return ServletActionContext.getServletContext().getResourceAsStream(
     "/upload/" + fileName);
}

@Override
public String execute() throws Exception {
   return SUCCESS;
}

}

进行struts.xml的配置,配置的主要代码如下:

   <action name="download" class="com.upload.struts2.action.DownloadAction">
   <result name="success" type="stream">
    <param name="contentType">application/vnd.ms-word</param>
    <param name="contentDisposition">filename=“test.doc”</param>
    <param name="inputName">downloadFile</param>
   </result>
   </action>

在进行配置的时候,里面的contentType为要下载的文件对应的MIME类型,inputName标签中的值是在Action中定义的获取inputStream的方法名称,一定要保证它们是一致的,即这里的getDownloadFile()与downloadFile名称是一致的。

如果想要动态地获取文件的名称,因为在Action中,已经有了fileName这个属性,就可以在struts.xml中直接调用。方法为 <param name="contentDisposition">filename=${fileName}</param>把原来的替换掉就可以了。

其它的几个属性,比如contentType,buffer之类的都可以通过类似的方法来设置。

附加:
---------------------------
上面支持下载文件类型为word文档,如果想支持多种格式下载需要把contentType
配置活,操作如下:
修改配置文件:
<param name="contentType">${contentType}</param>
修改Action类:
//输出流Content Type   
    public String contentType;   
    public void setContentType(String contentType) {
this.contentType = contentType;
     }

    public String getContentType() {
return contentType;
     }
public InputStream getDownloadFile() {
   System.out.println("成功下载附件:"+fileName);
   //获取格式
   String f=fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
   System.out.println("下载格式为"+f);
   if(f.equals("xls")){
   contentType = "application/vnd.ms-excel";   
   }else if(f.equals("doc") || f.equals("docx")){
   contentType = "application/vnd.ms-word"; 
   }
   return ServletActionContext.getServletContext().getResourceAsStream(
     "/uploadimage/" + fileName);
}
备注:具体struts支持的下载类型格式参考一下网站:http://www.w3schools.com/media/media_mimeref.asp