栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java文件下载

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java文件下载

此处文件下载使用get请求,是因为扩展迅雷下载时发现迅雷下载的时候一直使用get请求进行下载。 文件下载

1.ResponseEntity方式文件下载

注:此方式基于SpringMVC

@GetMapping("/responseEntityDownload")
public ResponseEntity downFile(){
    File file = new File("E:\文件上传测试", "mmexport1600165842010.jpg");
    byte[] bytes = new byte[0];
    try (
        // 高效文件读取流
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    ) {
        bytes = new byte[bis.available()];
        bis.read(bytes);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    //将要下载文件内容返回
    HttpHeaders httpHeaders = new HttpHeaders();
    // httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    // httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode(file.getName(),"UTF-8"));
    // 两种设置方式都可。
    // httpHeaders.set("Content-Disposition","attachment;filename="+ file.getName() +"");
    httpHeaders.set("Content-Disposition","attachment;filename="+ file.getName() +"");
    ResponseEntity requestEntity = new ResponseEntity(bytes,httpHeaders, HttpStatus.OK);
    return requestEntity;
}

2.response下载

    @GetMapping("/responseWhileDownload")
    public void responseWhileDownload(HttpServletResponse response) throws IOException {
        File file = new File("E:\文件上传测试", "WPS_Setup_11830.exe");
        byte[] bytes = null;
        // response重置
        response.reset();
        // 设置编码
        response.setCharacterEncoding("UTF-8");
        // 设置流
        response.setContentType("application/octet-stream");
        // 设置header
        response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(file.getName(),"UTF-8") +"");
        // 设置header告知大小
        response.addHeader("Content-Length", "" + file.length());
        ServletOutputStream outputStream = response.getOutputStream();
        try (
                // 高效文件读取流
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                // response输出流
                BufferedOutputStream bos = new BufferedOutputStream(outputStream)
        ) {
            bytes = new byte[8192];
            int length = 0;
            // 读取完毕后会返回-1,故结束循环
            while ((length = bis.read(bytes)) != -1){
                bos.write(bytes, 0, length);
            }
            bis.close();
            // 输出流切记要关闭不然无法完成下载
            bos.close();
            // response的输出流也必须关闭不然后台全是报错
            outputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
 前端代码
    ResponseEntity方式文件下载
response方式文件下载

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/999085.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号