基于SpringBoot实现后端压缩文件下载输出到前端

       下载压缩文件和下载其他文件的写法是一样的因为都是操作的字节流,通过IO流实现先将文件读取出来,然后再输出到浏览器。

@RestController
public class DownloadController {

    @Autowired
    private HttpServletResponse response;

    @GetMapping("/downloadFile")
    public void downloadFile(){
        String path = "G:\\document.zip";
        File file = new File(path);
        if(file.exists()){
            String fileName = file.getName();
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            download(response,file);
        }
    }


    public void download(HttpServletResponse response,File file){
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        OutputStream os = null;

        try {
            os = response.getOutputStream();
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            byte[] buffer = new byte[1024];
            int len = 0;
            while((len = fis.read(buffer)) != -1){
                os.write(buffer, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            bis.close();
            fis.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用postman测试就可以了,点击send下面的send and Download就会弹出提示框选择保存文件路径,然后就可以下载文件了。

 我们在写这样的代码是有事下载下载的zip文件打卡显示错误,这个问题一般都是在读缓冲区的时候出的问题,仔细分析以这段下代码是否有误,是否能完整输出字节缓冲区的数据。

byte[] buffer = new byte[1024];
int len = 0;
while((len = fis.read(buffer)) != -1){
os.write(buffer, 0, len);
}

补充: 如果使用类加载器的方式获取文件名或者文件流对象,需要注意的是pom文件里要添加以下标签,目的是防止zip被idea编译.  否则打开压缩包会出现"不可预料的文件末端"这样的错误.原因是代码在编译时会将我们上传到resources目录下的zip文件也进行编译,导致文件出现错误.

<build>
        <plugins>
            <plugin>
                <configuration>
                    <encoding>UTF-8</encoding>
                    <nonFilteredFileExtensions>
                        <nonFilteredFileExtension>zip</nonFilteredFileExtension>
                    </nonFilteredFileExtensions>
                </configuration>
            </plugin>
        </plugins>
</build>

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值