SpringBoot 批量下载阿里云文件,打ZIP包(URL,非OSS)

刚遇到个需求,

批量下载文件(这边用的阿里云的文件存储,所以有的都是文件的URL,不限文件类型)

下面是代码:

Controller:

@GetMapping("download")
    @ApiOperation("文件下载")
    public void download(@ApiIgnore @RequestParam String[] urls, HttpServletResponse response) throws IOException {
        response.setHeader("Content-Disposition",
                "attachment;filename=" +
                        new String("files.zip".getBytes("GB2312"),
                                "ISO-8859-1"));  // 需要编码否则中文乱码
        response.setContentType("application/zip;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        billFileService.download(urls, response.getOutputStream());
    }

Service:

/**
     * 文件下载
     * @param urls
     * @param outputStream
     */
    @Override
    public void download(String[] urls, ServletOutputStream outputStream) {

        ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
        InputStream in = null;
        HttpURLConnection conn = null;
        try {
            for(String urlPath : urls) {
                URL url = new URL(urlPath);
                conn = (HttpURLConnection)url.openConnection();
                //以Post方式提交表单,默认get方式
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                // post方式不能使用缓存
                conn.setUseCaches(false);
                //连接指定的资源
                conn.connect();
                in = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(in);

                ZipEntry entry = new ZipEntry(urlPath.substring(urlPath.lastIndexOf("/"), urlPath.length()));
                zipOutputStream.putNextEntry(entry);

                byte[] bt = new byte[4096];
                int read = 0;
                while((read = bis.read(bt)) != -1) {
                    zipOutputStream.write(bt, 0, read);
                }
                in.close();
                conn.disconnect();
            }
            conn.disconnect();
        } catch (Exception e) {
            throw new RenException("下载文件异常! \n" + e.getMessage());
        } finally {
            if(zipOutputStream != null) {
                try {
                    zipOutputStream.flush();
                    zipOutputStream.close();
                    outputStream.flush();
                    outputStream.close();

                } catch (Exception e) {
                    throw new RenException("下载文件关闭流异常!");
                }
            }
        }
   }
【注意】
while((read = bis.read(bt)) != -1) {
    zipOutputStream.write(bt, 0, read);
}

我之前是直接write(bt);

导致文件会损坏!

另外,关于前端的话,我没写,但是看了有推介用:

window.location.href = "/download";

你可能感兴趣的:(SpringBoot 批量下载阿里云文件,打ZIP包(URL,非OSS))