passer1991

struts2 annotation方式的下载(实用版)

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.ResultPath;
import org.apache.struts2.convention.annotation.Results;
import com.opensymphony.xwork2.ActionSupport;
@ResultPath("/")
@Results(value={
        @Result(name="success", type="stream",params={"contentType","application/octet-stream;charset=utf-8","inputName","inputStream","contentDisposition","attachment;filename=${fileName}","bufferSize","4096"})
})
public class DownloadAction extends ActionSupport {
    private String fileName;
    private InputStream inputStream;
    public void setFileName(String fileName) {
        this.fileName = fileName;
    }
    public InputStream getInputStream() {
        InputStream tempInputStream= (InputStream) ServletActionContext.getRequest().getAttribute("inputStream");
        String tempFileName= (String) ServletActionContext.getRequest().getAttribute("fileName");
        this.setFileName(tempFileName);
        return tempInputStream;
    }

    public String getFileName() {
        String temp=this.fileName;
        {        
            try {
                this.fileName =  new String(temp.getBytes(), "ISO8859-1"); 
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }   
        }
        return fileName;
    }
}

 

public class DemoAction extends ActionSupport {
	//通过在params中配置namespace参数,就可以改变action的命名空间
	@Action(value="downloadDemo",results={@Result(name="downloadDemo", type="chain",params={"namespace","/"},location="download")})
	public String downloadDemo() throws FileNotFoundException
	{
		InputStream inputStream=new FileInputStream(new File("c:/test.xls")) ;
		ServletActionContext.getRequest().setAttribute("inputStream", inputStream);
		ServletActionContext.getRequest().setAttribute("fileName", "中文test.xls");
		return "downloadDemo";
	}
}

  还可以这样,将actionName也放入params里,而不是使用location

public class DemoAction extends ActionSupport {
    //通过在params中配置namespace参数,就可以改变action的命名空间
    @Action(value="downloadDemo",results={@Result(name="downloadDemo", type="chain",params={"namespace","/","actionName","download"}})
    public String downloadDemo() throws FileNotFoundException
    {
        InputStream inputStream=new FileInputStream(new File("c:/test.xls")) ;
        ServletActionContext.getRequest().setAttribute("inputStream", inputStream);
        ServletActionContext.getRequest().setAttribute("fileName", "中文test.xls");
        return "downloadDemo";
    }
}

 

 http://localhost:8080/wang/downloadDemo.action

posted on 2013-03-20 10:29  passer1991  阅读(300)  评论(0编辑  收藏  举报

导航