structs2 文件下载

来源:互联网 发布:奥斯维辛集中营 知乎 编辑:程序博客网 时间:2024/06/07 10:50

download 的action

package app.sys.action;import app.common.action.GenericActionSupport;import org.apache.struts2.ServletActionContext;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;/** * @Desc * @Author LiMeng_season * @Date 2016/11/5 */public class download extends GenericActionSupport{//这个地方可以写成 ActionSupport.    private String fileName;    public String getFileName() {        return fileName;    }    public void setFileName(String fileName) {        this.fileName = fileName;    }    //返回一个输入流,作为一个客户端来说是一个输入流,但对于服务器端是一个 输出流    public InputStream getDownloadFile() throws Exception    {            this.fileName = "C:\\Users\\Administrator\\Pictures\\Saved Pictures\\ganta2.jpg";            //获取资源路径            InputStream is= new FileInputStream(new File(this.fileName));            return is;    }    @Override    public String execute() throws Exception {        return SUCCESS;    }}

sturts2配置

<action name="FileDownload" class="app.sys.action.download">            <result name="success" type="stream">                <param name="contentType">text/plain</param>                <param name="contentDisposition">attachment;fileName="${fileName}"</param>                <param name="inputName">downloadFile</param>                <param name="bufferSize">1024</param>            </result>        </action>

页面请求:

<html><body><h2>Hello World!</h2><button onclick="download()">下载</button></body><script src="js/jquery.min.js"></script><script>    function download(){        window.location.href="/FileDownload";    }</script></html>

作者依照了http://blog.csdn.net/hzc543806053/article/details/7538723。
当按照上面那篇博文写的时候,出现了
Can not find a java.io.InputStream with the name [downloadFile] in the invocation stack.
的错误。

所以将:

public InputStream getDownloadFile() throws Exception      {             this.fileName = "Dream.jpg" ;             //获取资源路径             return ServletActionContext.getServletContext().getResourceAsStream("upload/Dream.jpg") ;      }  

改成了:

public InputStream getDownloadFile() throws Exception    {            this.fileName = "C:\\Users\\Administrator\\Pictures\\Saved Pictures\\ganta2.jpg";            //获取资源路径            InputStream is= new FileInputStream(new File(this.fileName));            return is;    }

更多的信息请到原作者那篇上查看。

0 0
原创粉丝点击