Java 多附件zip下载完整代码

发布于:2024-04-01 ⋅ 阅读:(54) ⋅ 点赞:(0)

需求: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();
    }
}

本文含有隐藏内容,请 开通VIP 后查看

网站公告

今日签到

点亮在社区的每一天
去签到