项目需要用到文件下载功能,试了很多方式,在下载的时候response返回都会报错,后面找到了解决方法,源码如下:

public void download(String url, HttpServletResponse httpServletResponse) {
 		String filePath = String.format("%s/%s", System.getProperty("user.dir"), url);
        File file = new File(filePath);
        httpServletResponse.setHeader("content-type", "application/octet-stream;charset=utf-8");
        httpServletResponse.setContentType("application/octet-stream");
        try {
            httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = httpServletResponse.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(file));
            int i = bis.read(buff);
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();
                i = bis.read(buff);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
   }
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐