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
0
投稿
猜你喜欢
- 本文实例为大家分享了java实现二分法查找出数组重复数字的具体代码,供大家参考,具体内容如下package offer;/** * 二分查找
- android线程消息机制主要由Handler,Looper,Message和MessageQuene四个部分组成。平常在开发中,我们常用来
- java HashMap多层嵌套package chapter12;import java.util.HashMap;public clas
- 为大家分享的解决MyEclipse中的Building workspace问题的方法如下方法一:点击“Project”,取消勾选“Build
- 本文实例讲述了Java数组队列概念与用法。分享给大家供大家参考,具体如下:一.队列的概念 (1)队列也是一种线性结构(2)相比数组
- 本文所述为一个由C#编写的音乐播放器的主Form代码,里面有一些小技巧还是不错的,现共享给大家参考一下。里面有播放器背景设置、线程定义、调用
- 一般来说,修改框架的源代码是极其有风险的,除非万不得已,否则不要去修改。但是今天却小心翼翼的重构了Mybatis官方提供的与Spring集成
- 引言Random类是非常值得学习的一个类,所以我们今天一起学习一下Random这个类,对于模拟数据这个是随机类可是一个好东西,我们可以用这个
- 1.先导入以下两个jar包2.jsp文件表单必须是post提交,编码必须是multipart/form-data 文件上传文本框必须起名。3
- 一、手机版本问题,大多数文章没有涉及这个点,导致他们的代码并无法正常使用M版本以上需要使用的Type--> TYPE_APPLICAT
- 前言单元测试是编写测试代码,用来检测特定的、明确的、细颗粒的功能。单元测试并不一定保证程序功能是正确的,更不保证整体业务是准备的。单元测试不
- 查询返回Map<String,Object>类型mybatis 查询返回Map<String,Object> 类型,
- 1. 你知道线程安全问题吗?线程安全问题:一般指在多线程模式下,多个线程对同一个共享数据进行操作时,第一个线程还没来得及更新共享数据,从而导
- 这篇文章是博主在通过学习Android Studio的同时,实现service项目中用于背景音乐的实现,邮件的发送用于随堂小测的发送邮件功能
- 【题目】 汉诺塔问题比较经典,这里修改一下游戏规则:现在限制不能从最左侧的塔直接移动到最右侧,也不能从最右侧直接移动到最左侧,而是必须经过中
- 因为某些需求,要在特定的时间执行一些任务,比如定时删除服务器存储的数据缓存,定时获取数据以及定时发送推送等等,这时就需要用到定时任务了。定时
- 前言在实际生活中,地图是我们经常使用的一种工具,通常我们会用它进行导航,输入一个出发城市,输入一个目的地城市,就可以把路线规划好,而在规划好
- 先上效果图这个效果来自于三星S5的充电界面,当然有些细节差别,主要看思路.本文目的是技术交流,不要将效果直接运用于商业产品和项目.电池背景因
- Java 实现汉字转换为拼音转换类public class PINYINChinese { private static int
- Idea运行单个main方法,不编译整个工程直接上图1、选择main方法类右键->create ‘类名.main&