SpringMvc框架Java文件流下載。

// Spring這裏是通過實現ServletContextAware接口來注入ServletContext對象
    private ServletContext servletContext;

    @RequestMapping("/download")
    public void download(HttpServletResponse response) {
        InputStream ins = null;
        BufferedInputStream bins = null;
        OutputStream outs = null;
        BufferedOutputStream bouts = null;
        try {
            String path = servletContext.getRealPath("/");
            File file = new File(path + "download/" + "request.zip");
            String finalZipName = "request.zip";
            ins = new FileInputStream(file);
            bins = new BufferedInputStream(ins);// 放到緩衝流裏面
            outs = response.getOutputStream();// 獲取文件輸出IO流
            bouts = new BufferedOutputStream(outs);
            response.setContentType("application/x-download");// 設置response內容的類型
            response.setHeader("Content-disposition", "attachment;filename="
                    + URLEncoder.encode(finalZipName, "UTF-8"));// 設置頭部信息
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = bins.read(buffer, 0, 8192)) != -1) {
                bouts.write(buffer, 0, bytesRead);
            }
            bouts.flush();
//            System.out.println(bouts.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bins != null) {
                try {
                    bins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outs != null) {
                try {
                    outs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bouts != null) {
                try {
                    bouts.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void setServletContext(ServletContext servletContext) {
        // TODO Auto-generated method stub
        this.servletContext = servletContext;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章