java 文件流的处理方式 文件打包成zip

 更新时间:2021年10月19日 09:52:50   作者:介寒食  
这篇文章主要介绍了java 文件流的处理方式 文件打包成zip,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

java 文件流的处理 文件打包成zip

1、下载文件到本地

public void download(HttpServletResponse response){
    String filePath ="";//文件路径
    String fileName ="";//文件名称
    // 读到流中
    InputStream inStream = new FileInputStream(filePath);
    // 设置输出的格式
    response.reset();
     response.setContentType("bin");
     response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
     IOUtils.copy(inStream, response.getOutputStream());
}

2、java后端下载

方式一:

new URL(fileUrl + item.getcBhFileserver()).openStream()

方法二:

    public Boolean addFile(String url, String id, String fileName) { 
        RequestCallback requestCallBack = new RequestCallback() {
 
            @Override
            public void doWithRequest(ClientHttpRequest request) throws IOException {
                request.getHeaders().add("accept", MediaType.APPLICATION_OCTET_STREAM_VALUE);
            }
        };
 
        ResponseExtractor<Boolean> responseExtractor = new ResponseExtractor<Boolean>() { 
            @Override
            public Boolean extractData(ClientHttpResponse response) throws IOException {
                if (response.getStatusCode() == HttpStatus.OK) {
                    //得到文件流
                    InputStream input = response.getBody();
                    return true;
                }
                return false;
            }
        };
        return restTemplate.execute(url, HttpMethod.GET, requestCallBack, responseExtractor, id);
    }

3、文件打包成zip

public void zipFilesAll() throws Exception {
        String zipPath = "";//zip包路径
        String zipFileName = "";//zip包名称
        File zipFile = new File(zipFileName .toString());
 
        // 创建 FileOutputStream 对象
        FileOutputStream fileOutputStream = null;
        // 创建 ZipOutputStream
        ZipOutputStream zipOutputStream = null;
        try {
            //创建文件夹
            zipFile = new File(zipPath );
            FileUtils.forceMkdir(zipFile);
 
            //创建文件
            zipFile = new File(zipFileName .toString());
            if (!zipFile.exists()) {
                zipFile.createNewFile();
            }
 
            // 实例化 FileOutputStream 对象
            fileOutputStream = new FileOutputStream(zipFileName.toString());
            // 实例化 ZipOutputStream 对象
            zipOutputStream = new ZipOutputStream(fileOutputStream);
            // 创建 ZipEntry 对象
            ZipEntry zipEntry = null;
            for (CL cl: ClList) {
                // 实例化 ZipEntry 对象,源文件数组中的当前文件
                zipEntry = new ZipEntry(tCltjjl.getcClmc() + ".zip");
                zipOutputStream.putNextEntry(zipEntry);
                IOUtils.copy(new FileInputStream(cl.getcPath(), zipOutputStream);
            }
        } catch (Exception e) {
             
        }finally{
             //记得删除文件
        }
    }   

后台多文件打包成zip返回流 前台提供按钮一键下载

项目pom文件添加二维码操作,和文件打包的maven支持:

        <!--二维码相关 start-->
        <dependency>
            <groupId>net.glxn.qrgen</groupId>
            <artifactId>javase</artifactId>
            <version>2.0</version>
        </dependency>
        <!--二维码相关 end-->
 
        <!--文件打包相关 start-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.12</version>
        </dependency>
        <!--文件打包相关 end-->

前台代码:

<button type="button" onclick="downloadzip()">下载</button>

js(我用了thymeleaf模板)代码:

<script th:inline="javascript">
    function downloadzip(){
 
            var storeType = $("#storeType").val();
            if(storeType ==""){
                bootAlertError("请选择门店!");
                return;
            }
            var url = [[@{/downLoadProductQrCode/getStreamZip}]];
 
            //模拟form表单 返回打包流
            var form = $('<form method= "POST" action="'+ url +'" enctyped="multipart/form-data">'+
                        '<input name= "agencyId" type= "hidden" value="'+storeType+'" />'
                        +'</form>');
            form. appendTo('body'). submit(). remove();
        }
</script>

后台代码:

/**
     * @Author Ni Klaus
     * @Description //TODO 门店总代生成打包产品二维码zip
     * @Date 上午 10:38 2019/8/20 0020
     * @Param [params,response]
     * @return void
     **/
    @RequestMapping({"getStreamZip"})
    @ResponseBody
    public void findList(@RequestParam Map params,HttpServletResponse response) throws Exception {
        String agencyId = (String) params.get("agencyId");
        AgencyAccount agencyAccount = agencyAccountService.getAccountByAgencyId(agencyId);
        //这里设置打包后的zip文件名
        String downloadName = agencyAccount.getName()+".zip";
        try{
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(downloadName.getBytes(),"ISO8859-1"));
        }catch(UnsupportedEncodingException e){
            log.error("----------下载文件名编码时出现错误------"+e.getMessage());
        }
        OutputStream outputStream = response.getOutputStream();
        ZipArchiveOutputStream zous = new ZipArchiveOutputStream(outputStream);
        zous.setUseZip64(Zip64Mode.AsNeeded);
        zous.setEncoding("utf-8");
        try{
            //我这里是通过不同产品类型生成不同产品的二维码图片流
            //具体你想生成什么类型的多个文件打包,只需要循环创建ArchiveEntry 然后zous.putArchiveEntry(entry)就可以了
            StoreProductType[] storeProductTypes = StoreProductType.values();
            for (StoreProductType storeProductType : storeProductTypes) {
                String url = "http://m.xxx.cn/goods/pay/xxx.html?productid="+storeProductType.getProductId()
                        + "&agencycode="+ agencyId +"&channelid=def&appfrom=sqjk&isstore=1";
                //打包文件里的每个文件的名字
                String imgName = storeProductType.getDescription()+".png";
                ByteArrayOutputStream out = QRCode.from(url).to(ImageType.PNG).withSize(300,300).stream();
                byte[] bytes = out.toByteArray();
                ArchiveEntry entry = new ZipArchiveEntry(imgName);
                zous.putArchiveEntry(entry);
                zous.write(bytes);
                zous.closeArchiveEntry();
                if (out != null) {
                    out.close();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("---------------门店总代生成二维码打包流出错----------------"+e.getMessage());
        }finally{
            if(outputStream != null){
                outputStream.close();
            }
            if(zous != null){
                zous.close();
            }
        }
    }

最后效果:

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • SpringBoot Entity中枚举类型详细使用介绍

    SpringBoot Entity中枚举类型详细使用介绍

    本文介绍SpringBoot如何在Entity(DAO)中使用枚举类型。(本文使用MyBatis-Plus)。在实际开发中,经常会遇到表示类型或者状态的情况,比如:有三种支付方式:微信、支付宝、银联。本文介绍如何这种场景的方案对比,并用实例来介绍如何用枚举这种最优雅的来表示
    2022-10-10
  • Mybatis基于注解与XML开发使用流程

    Mybatis基于注解与XML开发使用流程

    MyBatis是Java的持久化框架,目的是为了使操作数据库更加方便、灵活、高效,可以通过Java注解和XML文件来映射Java对象和SQL语句,提供了非常灵活的SQL编写方式和动态SQL语句的创建方式,这篇文章主要介绍了Mybatis基于注解与XML开发,需要的朋友可以参考下
    2023-07-07
  • springboot接入微信app支付的方法

    springboot接入微信app支付的方法

    本文使用springboot集成微信支付服务,包含微信统一支付订单接口,以及支付回调接口等,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-05-05
  • Java数据结构之顺序表和链表精解

    Java数据结构之顺序表和链表精解

    我在学习完顺序表后一直对顺序表和链表的概念存在一些疑问,这里给出一些分析和看法,通读本篇对大家的学习或工作具有一定的价值,需要的朋友可以参考下
    2021-09-09
  • JustAuth-第三方Oauth2登录方式

    JustAuth-第三方Oauth2登录方式

    JustAuth是一款支持多种第三方登录的工具,本文通过实战介绍了如何在Springboot项目中集成JustAuth实现第三方登录,主要步骤包括引入依赖、配置Controller、设置登录和回调页面,通过访问登录页面并选择Gitee登录,系统会重定向至Gitee进行认证
    2024-09-09
  • Java8新特性之方法引用的实践指南

    Java8新特性之方法引用的实践指南

    这篇文章主要给大家介绍了关于Java8新特性之方法引用的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2021-03-03
  • Java关于BeabUtils.copyproperties的用法

    Java关于BeabUtils.copyproperties的用法

    这篇文章主要介绍了Java关于BeabUtils.copyproperties的用法,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2024-08-08
  • Java基础之反射

    Java基础之反射

    JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;反射是框架设计的灵魂,感兴趣的小伙伴可以参考阅读
    2023-03-03
  • Mybatis的collection三层嵌套查询方式(验证通过)

    Mybatis的collection三层嵌套查询方式(验证通过)

    这篇文章主要介绍了Mybatis的collection三层嵌套查询方式(验证通过),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • 浅谈springboot 属性定义

    浅谈springboot 属性定义

    本篇文章主要介绍了浅谈springboot 属性定义,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-08-08

最新评论