fastDFS批量文件下载,打包zip格式

fastdfs官方github地址:https://github.com/happyfish100/fastdfs

前言官方的storageClient.download_file1(filepath)下载目前只支持单文件下载,如果需要实现批量下载目前需要自己组装,刚好目前项目有这个需求,所以把实习方式共享出来,目前源码支持打包成jar,欢迎下载
csdn官方下载 https://download.csdn.net/download/haibo8023/12655412

一、下载示例

需求描述

@ApiOperation("批量下载附件")
    @GetMapping("/downloadAttachments/{noticeId}")
    public void downloadAttachments(@PathVariable("noticeId") Long noticeId,HttpServletRequest request,HttpServletResponse response){
        noticeService.downloadAttachments(noticeId,request,response);
    }
@Override
    public void downloadAttachments(Long noticeId, HttpServletRequest request, HttpServletResponse response) {
        Notice notice = mapper.selectByPrimaryKey(noticeId);
        if (Objects.isNull(notice) || Objects.equals(notice.getType(), NoticeTypeEnum.NOTICE.getId())) {
            return;
        }
        List<String> strings = noticeRangeMapper.selectByNoticeId(noticeId);
        List<NoticeAttachmentDto> attachments = new ArrayList<>();
        for (String string : strings) {
            ArrayList<NoticeAttachmentDto> noticeAttachmentDtos = JSON.parseObject(string, new TypeReference<ArrayList<NoticeAttachmentDto>>() {
            });
            attachments.addAll(noticeAttachmentDtos);
        }
        List<String> fileUrls = attachments.stream().filter(s -> StringUtils.isNotEmpty(s.getPath())).map(s -> {
            try {
                return URLDecoder.decode(s.getPath(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return null;
        }).collect(Collectors.toList());
        CommonUtils.setResponseHeader("任务批量附件下载.zip", request, response);
        FastDFSClient.download(fileUrls, request, response);
    }

下载完成

二、核心实现方法

 /**
     * 批量下载fastDFS文件
     *
     * @param filepaths
     * @param zipFileName
     * @param request
     * @param response
     */
    public static void download(List<String> filepaths, String zipFileName, HttpServletRequest request, HttpServletResponse response) {
        if (response == null) {
            throw new FastDFSException(RESPONSE_IS_NULL);
        }
        if (CollectionUtils.isEmpty(filepaths)) {
            throw new FastDFSException(FILE_PATH_IS_NULL);
        }
        setResponseHeader(zipFileName, request, response);
        try {
            byte[] buffer = new byte[1024];
            // 创建一个新的 byte 数组输出流,它具有指定大小的缓冲区容量
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            //创建一个新的缓冲输出流,以将数据写入指定的底层输出流
            BufferedOutputStream fos = new BufferedOutputStream(baos);
            ZipOutputStream zos = new ZipOutputStream(fos);
            for (int i = 0; i < filepaths.size(); i++) {
                //获取各个文件的数据流
                String filepath = toLocal(filepaths.get(i).trim());
                // Get the file name
                String filename = getOriginalFilename(filepath);
                log.debug("Download file, the file path is: {}, filename: {}", filepath, filename);
                InputStream fis = getFileInputStream(filepath);
                //压缩文件内的文件名称
                zos.putNextEntry(new ZipEntry(filename));
                int length;
                while ((length = fis.read(buffer)) > 0) {
                    //将文件读入压缩文件内
                    zos.write(buffer, 0, length);
                }
                zos.closeEntry();
                fis.close();
            }
            zos.close();
            fos.flush();

            try (
                    OutputStream _os = response.getOutputStream();
                    InputStream is = new ByteArrayInputStream(baos.toByteArray());
            ) {

                byte[] buffer1 = new byte[1024 * 5];
                int len = 0;
                while ((len = is.read(buffer1)) > 0) {
                    _os.write(buffer1, 0, len);
                }
                _os.flush();
            } catch (IOException e) {
                log.error(FILE_WRITE_FAILED.getCode(), e);
                throw new FastDFSException(FILE_WRITE_FAILED, e);
            }
        } catch (Exception ioe) {
            ioe.printStackTrace();
        }
    }
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

haibo8023

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值