Java web网页文件下载功能

1 通过字节流方式

    public static void downloadByStream(HttpServletResponse response, File file) {
        response.setContentType("application/force-download");
        // 设置强制下载不打开
        response.setContentType("multipart/form-data;charset=UTF-8");
        //也可以明确的设置一下UTF-8,测试中不设置也可以。
        response.setHeader("Content-Disposition", "attachment;fileName=" + file.getName());
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            OutputStream os = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(os);
            int len = bis.read(buffer);
            while (len != -1) {
                bos.write(buffer, 0, len);
                len = bis.read(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

2 通过ResponseEntity<byte[]>方式

    public static ResponseEntity<byte[]> downloadByResponseEntity(File file) throws IOException {
        ResponseEntity.BodyBuilder bodyBuilder = ResponseEntity.ok();
        bodyBuilder.contentLength(file.length());
        bodyBuilder.contentType(MediaType.APPLICATION_OCTET_STREAM);
        bodyBuilder.header("Content-Disposition", "attachment;filename=" +
                new String(file.getName().getBytes("UTF-8"), "iso-8859-1"));
        return bodyBuilder.body(FileUtils.readFileToByteArray(file));
    }

这是我目前接触到的方法,原理了解得不深,属于会用的程度~~

猜你喜欢

转载自blog.csdn.net/weixin_46269980/article/details/106266891
今日推荐