0


Java实现文件下载zip包单文件等

Java实现文件压缩包(zip)下载

摘要

本次主要记录将多个文件打包到zip压缩包并完成下载;留个代码方便以后用到了ctrl c v

1 多个文件打包成ZIP,下载zip包,单个文件下载

我使用的是hutool工具包的二次封装,下面直接列出工具类即可,具体API不再详述,需要详细了解的可以自行百度

注意:

1 工具类中文件参数都是以File对象接收的,如果你是远程URL下载文件的话,需要自行百度去将URL中的资源转为InputStream或者转为File对象;

2 此工具类的downloadAnyFile方法如果使用postman测试可能还会出现文件名中文乱码问题,但是我试过使用浏览器直接请求文件名不会出现乱码问题,也尝试了设置postman的请求头和响应头都与浏览器的保持一致,但是并没有效果…

packagemrkay.show.utils;importcn.hutool.core.collection.CollUtil;importcn.hutool.core.io.FileTypeUtil;importcn.hutool.core.util.ZipUtil;importlombok.extern.slf4j.Slf4j;importjavax.activation.MimetypesFileTypeMap;importjavax.servlet.http.HttpServletResponse;importjava.io.*;importjava.net.URLEncoder;importjava.nio.charset.StandardCharsets;importjava.util.List;/**
 * 自定义 (zip压缩包/文件) 操作工具类
 *
 * @author liukai
 * @date 2022/7/14
 */@Slf4j@SuppressWarnings("all")publicclassZipFileUtils{/**
     * 生成Zip压缩包 (注意是对hutool的二次封装,所以必须要有hutool依赖)
     *
     * @param targetZipFile 要生成的目标zip压缩包
     * @param sourceFiles   压缩包中包含的文件集合
     * @param dirWithFlag   是否将文件目录一同打包进去 (true:压缩包中包含文件目录,false:压缩包中不包含目录)
     * @author liukai
     */publicstaticvoidgenerateZip(File targetZipFile,List<File> sourceFiles,boolean dirWithFlag){if(CollUtil.isNotEmpty(sourceFiles)){File[] fileArr = sourceFiles.toArray(newFile[]{});ZipUtil.zip(targetZipFile, dirWithFlag, fileArr);}}/**
     * 下载ZIP压缩包(会对下载后的压缩包进行删除)
     *
     * @param file     zip压缩包文件
     * @param response 响应
     * @author liukai
     */publicstaticvoiddownloadZip(File file,HttpServletResponse response){OutputStream toClient =null;try{// 以流的形式下载文件。BufferedInputStream fis =newBufferedInputStream(newFileInputStream(file.getPath()));byte[] buffer =newbyte[fis.available()];
            fis.read(buffer);
            fis.close();// 清空response
            response.reset();
            toClient =newBufferedOutputStream(response.getOutputStream());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition","attachment;filename="+ file.getName());
            toClient.write(buffer);
            toClient.flush();}catch(Exception e){
            log.error("下载zip压缩包过程发生异常:", e);}finally{if(toClient !=null){try{
                    toClient.close();}catch(IOException e){
                    log.error("zip包下载关流失败:", e);}}//删除改临时zip包(此zip包任何时候都不需要保留,因为源文件随时可以再次进行压缩生成zip包)
            file.delete();}}/**
     * 任何单文件下载
     *
     * @param file     要下载的文件
     * @param response 响应
     * @author liukai
     */publicstaticvoiddownloadAnyFile(File file,HttpServletResponse response){FileInputStream fileInputStream =null;OutputStream outputStream =null;try{
            fileInputStream =newFileInputStream(file);// 清空response
            response.reset();//防止文件名中文乱码
            response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(file.getName(),"UTF-8"));//根据文件动态setContentType
            response.setContentType(newMimetypesFileTypeMap().getContentType(file)+";charset=UTF-8");
            outputStream = response.getOutputStream();byte[] bytes =newbyte[2048];int len;while((len = fileInputStream.read(bytes))>0){
                outputStream.write(bytes,0, len);}}catch(Exception e){
            e.printStackTrace();}finally{if(outputStream !=null){try{
                    outputStream.close();}catch(IOException e1){
                    e1.printStackTrace();}}if(fileInputStream !=null){try{
                    fileInputStream.close();}catch(IOException e1){
                    e1.printStackTrace();}}}}}

本文转载自: https://blog.csdn.net/weixin_44848900/article/details/125838828
版权归原作者 liu.kai 所有, 如有侵权,请联系我们删除。

“Java实现文件下载zip包单文件等”的评论:

还没有评论