Struts2 的文件下载

虽然说Struts2的下载是个小问题, 可是,有是忘记了,动手写还不容易。

网上的又是你C我的,我C你的,烦。

 

 

Struts2的下载其实很简单,只需要修改两个地方即可。

1、action的配置

 

 <action name="downloadfile" class="com.shenzhan.pro.util.DownloadfileAction">
           <result type="stream">
            <param name="contentType">application/octet-stream</param>
            <param name="inputName">inputStream</param>                                      <!-- 对应public InputStream getInputStream(); 返回文件流 -->
            <param name="contentDisposition">attachment;filename="${fileName}"</param>  <!-- public String getFileName();  返回文件名 -->
            <param name="bufferSize">4096</param>
           </result>
  </action>

 

 

 

 

2、两个方法 public InputStream getInputStream(); 返回文件流

                    public String getFileName();  返回提示的文件名

 

相应的Acption内容如下:

    package com.shenzhan.pro.util;

import java.io.InputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class DownloadfileAction extends ActionSupport {

private String filepath;  //这个是传入的文件路径,它在数据库里面是这样的 userupload/200912/20091215_104550_9381.rar                                                                       
 @Override
 public String execute() throws Exception {
  //这里可以设计权限
  if(filepath==null){
   return null;   //如果没有路径,返回空
  }
  return SUCCESS;
 }
 
 public InputStream getInputStream() throws Exception {
   String realpath="/"+filepath;  //必须是相对于根目录的绝对路径
   return ServletActionContext.getServletContext().getResourceAsStream(realpath);
 }
 
 public String getFileName(){
  int i=filepath.lastIndexOf("/")+1;
  return filepath.substring(i,filepath.length());
 }
 
 public String getFilepath() {
  return filepath;
 }

 public void setFilepath(String filepath) {
  this.filepath = filepath;
 }
}

你可能感兴趣的:(exception,String,Stream,struts,Class,action)