java 文件流的处理方式 文件打包成zip
作者:介寒食 发布时间:2022-07-08 12:43:03
标签: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();
}
}
}
最后效果:
来源:https://www.cnblogs.com/jiehanshi/p/11533465.html


猜你喜欢
- Spring 配置文件报错:元素 "context:component-scan" 的前缀 "context&
- 本文实例讲述了C#中static静态变量的用法。分享给大家供大家参考。具体如下:使用 static 修饰符声明属于类型本身而不是属于特定对象
- 自动装配的含义在SpringBoot程序main方法中,添加@SpringBootApplication或者@EnableAutoConfi
- 本文为大家分享两个实例,相信大家一定会喜欢。实例1:随机生成验证码图片并将之输出为一个png文件效果图:import java.awt.Co
- java中如何表示圆周率设计一个Shape接口和它的两个实现类Square和Circle。 要求如下(1) Shape接口中有一个抽象方法a
- 定时器问题定时器属于基本的基础组件,不管是用户空间的程序开发,还是内核空间的程序开发,很多时候都需要有定时器作为基础组件的支持。一个定时器的
- 本文实例为大家分享了Java实现简单GUI登录和注册界面的具体代码,供大家参考,具体内容如下先看效果图:登陆界面:注册界面:实现代码如下:一
- springboot集成 redispom文件<dependency> <groupId>
- 1、多态性多态性是面向对象的最后一个特征,它本身主要分为两个方面: 方法的多态性:重载与覆写1、重载:同一个方法名称,根据参数类型以及个数完
- 最近在做报表统计方面的需求,涉及到行转列报表。根据以往经验使用SQL可以比较容易完成,这次决定挑战一下直接通过代码方式完成行转列。期间遇到几
- 前言在使用easyExcel读取文件时,对于Excel的表头,在解析读取时分成不同的状态,需要加以区分.1 环境准备准备一个可以正常访问的S
- 很多人使用Nacos其实并没有真正的去读过官网,以至于忽视了很多重要的细节,Nacos为我们提供了大量API,但是这些API默认是没有开启认
- 一、分布式压测原理如下图(这个图说明的是要一台控制机,然后由这台控制机发压测脚本到每台远程执行机,然后由控制机收集执行机结果)二、修改 Jm
- 一、技术概述1、描述这个技术是做什么?是Unity一套网络工具库,用于进行Http请求2、学习该技术的原因?项目需要,防止使用C#原生的网络
- 学过C#的人应该都知道抽象方法与虚拟方法,而很多初学者对二者之间的区别并不是很了解。今天本文就来分析一下二者之间的区别。并附上实例加以说明。
- 本文实例讲述了Android自定义ViewPager的方法。分享给大家供大家参考,具体如下:package com.rong.activit
- 主要思路就是提供者持有密钥,通过RSA加密客户机标识或时间标识,再通过Base64加密成不太难看的注册码,然后分发给客户机。客户机解Base
- 前言之前写过一篇关于配置中心对配置内容加密解密的介绍:《Spring Cloud构建微服务架构:分布式配置中心(加密解密) 》。在这篇文章中
- #define Testusing System;namespace Wrox.ProCSharp.ParameterTestSample.
- 一. 引入相关jar包首先,我们先在idea里创建出一个Maven项目出来,除了路径要填成自己的希望路径以外,其他都可以一路next和fin