springboot下java文件下载

spring boot 上线会压缩文件 首先是要在pom中去除该后缀名文件的压缩,否者压缩后文件内容会导致乱码。

@RequestMapping(value = "/downloadFile")
    public void downloadFile(HttpServletResponse response,HttpServletRequest request) throws Exception{
        //linux线上适用
        ClassPathResource resource = new ClassPathResource("distributorDemo.xls");
        //windows适用
	String filePath = "./system/src/main/resources/distributorDemo.xls";

	File f = new File(new String(filePath.getBytes("ISO8859-1"),"utf-8"));
	BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));

        byte[] buf = new byte[1024];
        int len = 0;
            response.reset();
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename="
                    + (f.getName()));
        OutputStream out = response.getOutputStream();
            while ((len = br.read(buf)) > 0)
                out.write(buf, 0, len);
            out.flush();
            br.close();
            out.close();
    }

本文为记录贴,方便以后用到快速查找使用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章