使用response下载文件

将字节流写入http response, 注意设置响应头即可,浏览器会根据响应头做出下载文件的操作

示例

    @RequestMapping("/download")
    public void downloadTar(HttpServletResponse response) {
        OutputStream ous = null;
        InputStream ins = null;

        File file = new File(TAR_FILE_PATH);
        try {
            ins = new BufferedInputStream(new FileInputStream(file));
            byte []buffer = new byte[ins.available()];
            ins.read(buffer);

            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
            response.addHeader("Content-Length", "" + file.length());
            ous = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            ous.write(buffer);
            ous.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ins.close();
                ous.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

你可能感兴趣的:(java,web)