项目需要用到文件下载功能,试了很多方式,在下载的时候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

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐