Java 多附件zip下载完整代码

需求:Java根据Url把多个文件下载到指定的文件夹目录,然后再将文件夹目录打包成zip导出.

@Slf4j
@Controller("test")
@Api(value = "zip文件上传API", tags = {"zip文件上传"})
public class Download {
    @Autowired
    private RecordFileMapper recordFileMapper;
    @Autowired
    private AttachmentRepository attachmentRepository;
    /**
     * 文件下载
     * @param
     * @param response
     * @throws Exception
     */
    @GetMapping("checkDownloadFile")
    @ResponseBody
    public void checkDownloadFile(@ApiParam("id") @RequestParam("id") String id,
                              HttpServletResponse response) throws Exception {
 
        //根据id获取到你的文件url
        QueryWrapper<RecordFile> recordFileQueryWrapper = new QueryWrapper<>();
        recordFileQueryWrapper.eq("recordid", id);
        List<RecordFile> recordFileList = recordFileMapper.selectList(recordFileQueryWrapper);
        List<Attachment> attachmentList = new ArrayList<>();
        for (int k = 0; k < recordFileList.size(); k++) {
            //获取id
            if (recordFileList != null) {
                RecordFile recordFile = recordFileList.get(k);
                //根据文件id查询neo4j里面的文件信息
                Attachment attachment = attachmentRepository.queryByid(Long.valueOf(recordFile.getFileid()));
                attachmentList.add(attachment);
            }
        }
        //判断你的集合是否为=1,如果是1 是单个文件直接执行下面的代码
        if(attachmentList.size()==1){
            String url=attachmentList.get(0).getPath();
            HttpURLConnection conn = null;
            InputStream fis = null;
            try {
                File file = new File(url);
                // 取得文件的后缀名。
                String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();
                StringBuffer buffername = new StringBuffer(url.substring(url.lastIndexOf("/")+1));
                // 取的文件名
                String filename = buffername.toString();
                URL path = new URL(url);
                conn = (HttpURLConnection) path.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(5 * 1000);
                // 通过输入流获取数据
                fis = conn.getInputStream();
                byte[] buffer = readInputStream(fis);
                if (null != buffer && buffer.length > 0) {
                    // 清空response
                    response.reset();
                    // 设置response的Header
                    String [] name=filename.split("\\?");
                    response.addHeader("Content-Disposition", "attachment;filename=" +  new String(name[0].getBytes(),"ISO8859-1"));
                    response.addHeader("Content-Length", "" + buffer.length);
                    OutputStream toClient = response.getOutputStream();
                    //response.setContentType("application/x-msdownload");
                    response.setContentType("application/octet-stream");
                    toClient.write(buffer);
                    toClient.flush();
                    toClient.close();
                }
            } catch (IOException ex) {
                log.error("下载文件异常:", ex);
                throw new Exception("下载异常,请稍后再试。");
            } finally {
                if (conn != null) {
                    conn.disconnect();
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException ioe) {
                        log.error("下载文件->关闭流异常:", ioe);
                    }
                }
            }
        }else{
            //多个的需要先打包再下载
 
            //定义压缩地址
            String fileStr = "D:\\image\\";
            String zipFileStr =  "D:\\imageZip\\项目统计进展报告.zip";
            //构建map,执行压缩
            List<Map<String, String>> imageUrls = new ArrayList<>();
            Map<String, String> imageUrl = new HashMap<>();
            //循环构建map
            for(int i=0;i<attachmentList.size();i++){
                imageUrl.put(attachmentList.get(i).getName(), attachmentList.get(i).getPath());
                imageUrls.add(imageUrl);
            }
            FileZipUtils.FileMain(imageUrls,fileStr,zipFileStr);
            //下载文件
            String url=zipFileStr;
            try {
                // path是指欲下载的文件的路径。
                File file = new File(url);
                // 取得文件名。
                String filename = file.getName();
                // 取得文件的后缀名。
                String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(url));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 设置response的Header
                response.addHeader("Content-Disposition", "attachment;filename=" +  java.net.URLEncoder.encode(filename, "utf-8"));
                response.setContentType("text/html;charset=utf-8");
                response.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } catch (IOException ex) {
                log.error("下载文件异常:", ex);
                throw new Exception("下载异常,请稍后再试。");
            } finally {
                try {
                    //删除压缩包
                    File zfile = new File(url);
                    zfile.delete();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
 
    }
    @GetMapping("checkDownload")
    @ResponseBody
    public void checkDownload(@ApiParam("文件地址") @RequestParam("url") String url,
                              HttpServletResponse response) throws Exception {
        HttpURLConnection conn = null;
        InputStream fis = null;
        try {
            File file = new File(url);
            // 取得文件的后缀名。
            String ext = file.getName().substring(file.getName().lastIndexOf(".") + 1).toLowerCase();
            StringBuffer buffername = new StringBuffer(url.substring(url.lastIndexOf("/")+1));
            // 取的文件名
            String filename = buffername.toString();
 
            URL path = new URL(url);
            conn = (HttpURLConnection) path.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            // 通过输入流获取数据
            fis = conn.getInputStream();
 
            byte[] buffer = readInputStream(fis);
            if (null != buffer && buffer.length > 0) {
                // 清空response
                response.reset();
                // 设置response的Header
                String [] name=filename.split("\\?");
                response.addHeader("Content-Disposition", "attachment;filename=" +  new String(name[0].getBytes(),"ISO8859-1"));
                response.addHeader("Content-Length", "" + buffer.length);
                OutputStream toClient = response.getOutputStream();
                //response.setContentType("application/x-msdownload");
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            }
        } catch (IOException ex) {
            log.error("下载文件异常:", ex);
            throw new Exception("下载异常,请稍后再试。");
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ioe) {
                    log.error("下载文件->关闭流异常:", ioe);
                }
            }
        }
    }
 
    /**
     * 从输入流中获取数据
     *
     * @param fis : InputStream
     * @return byte[]
     * @author chenp
     * @date 2023/3/28 11:31
     */
    private byte[] readInputStream(InputStream fis) throws IOException {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = fis.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        fis.close();
        return outStream.toByteArray();
    }
}

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
你可以使用Java中的ZipOutputStream类来实现将多个附件打包成Zip文件并返回给前端。以下是一个简单的代码示例: ```java import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ZipServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取要打包的文件列表 String[] fileNames = request.getParameterValues("fileNames[]"); try { // 设置响应头 response.setContentType("application/zip"); response.setHeader("Content-Disposition", "attachment; filename=\"archive.zip\""); // 创建ZipOutputStream ServletOutputStream out = response.getOutputStream(); ZipOutputStream zipOut = new ZipOutputStream(out); // 添加文件到ZipOutputStream for (String fileName : fileNames) { File file = new File(fileName); FileInputStream in = new FileInputStream(file); ZipEntry zipEntry = new ZipEntry(file.getName()); zipOut.putNextEntry(zipEntry); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) { zipOut.write(buffer, 0, len); } in.close(); zipOut.closeEntry(); } // 关闭ZipOutputStream zipOut.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在这个代码示例中,我们首先从请求中获取要打包的文件列表,然后设置响应头以告诉浏览器返回的是一个Zip文件,并将ZipOutputStream对象的输出流设置为响应的输出流。接着,我们遍历文件列表,将每个文件添加到ZipOutputStream中。最后,我们关闭ZipOutputStream以确保Zip文件正确地生成并返回给前端。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

加瓦程序设计师

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

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

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

打赏作者

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

抵扣说明:

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

余额充值