文件下载

(1)不使用struts2提供的文件下载

Action类的处理代码:

public String download() throws Exception{

        //1:获取用户附件ID,查询用户附件对象,获取路径path

        String id = elecUser.getFileID();

        ElecUserFile elecUserFile = elecUserService.findElecUserFileByID(id);

        //路径path

        String path = elecUserFile.getFileURL();

        //下载时,使用的文件名

        String name = elecUserFile.getFileName();

        //处理中文问题,或者使用:name = URLEncoder.encode(name, "UTF-8");

        name = new String(name.getBytes("gbk"),"iso-8859-1");

        //2:使用response对象设置文件下载的信息(头部信息,文件类型…)

        response.setHeader("Content-disposition", "attachment;filename="+name+"");

        response.setBufferSize(1024);

        //3:使用InputStream输入流读到path路径下对应文件,将InputStream的输入流写到输出流(response对象中获取)中

        InputStream in = new FileInputStream(new File(ServletActionContext.getServletContext().getRealPath("")+path));

        OutputStream out = response.getOutputStream();

        for(int b=-1;(b=in.read())!=-1;){

            out.write(b);

        }

        out.close();

        in.close();

        return null;

    }

 

(2)使用struts2提供的文件下载

第一步:配置struts.xml

 

第二步:在模型驱动的对象中,添加InputStream类型的属性,用来存放文件的输入流

其中属性名称要与struts.xml中定义的inputName的值一致。

 

第三步:将查询的文件输入流放置到模型驱动定义的inputStream属性中,用来输出文件。

第四步:Action类中代码:

public String download() throws Exception{

        String id = elecUser.getFileID();

        ElecUserFile elecUserFile = elecUserService.findElecUserFileByID(id);

        //路径path

        String path = elecUserFile.getFileURL();

        //下载时,使用的文件名

        String name = elecUserFile.getFileName();

        //处理中文问题,或者使用:name = URLEncoder.encode(name, "UTF-8");

        name = new String(name.getBytes("gbk"),"iso-8859-1");

        request.setAttribute("filename", name);

       

        //2:使用InputStream输入流读到path路径下对应文件

        InputStream in = new FileInputStream(new File(ServletActionContext.getServletContext().getRealPath("")+path));

        //将输入流压入到栈顶

        elecUser.setInputStream(in);

        return "fileSuccess";

    }

posted @ 2016-07-18 20:13  kimi9py  阅读(110)  评论(0编辑  收藏  举报