java 文件流的处理方式 文件打包成zip
作者:介寒食 时间:2022-07-08 12:43:03
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
标签:java,文件流,文件打包,zip
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
WPF调用ffmpeg实现屏幕录制
2023-04-23 13:57:00
![](https://img.aspxhome.com/file/2023/3/111073_0s.gif)
c# 空合并运算符“??”的使用详解
2022-11-23 13:47:36
Android巧用XListView实现万能下拉刷新控件
2023-07-25 00:33:03
Android 四种动画效果的调用实现代码
2021-06-26 17:59:54
![](https://img.aspxhome.com/file/2023/4/126764_0s.gif)
eclipse中自动生成javadoc文档的方法
2022-04-08 17:54:12
解决springboot生成bean名称冲突(AnnotationBeanNameGenerator)
2023-01-09 22:27:11
![](https://img.aspxhome.com/file/2023/0/125240_0s.png)
Java向上转型和向下转型实例解析
2022-08-12 01:59:28
Struts2实现多文件上传功能
2021-11-01 13:50:25
![](https://img.aspxhome.com/file/2023/8/69098_0s.png)
使用Java开发实现OAuth安全认证的应用
2023-07-16 13:55:44
![](https://img.aspxhome.com/file/2023/7/64917_0s.png)
C#时间格式转换为时间戳的方法步骤
2022-04-13 12:27:19
Java项目开发命名规范(动力节点Java学院整理)
2021-06-24 07:16:56
Android编程实现自动检测版本及自动升级的方法
2023-06-07 16:24:23
![](https://img.aspxhome.com/file/2023/0/98640_0s.jpg)
C#逆变与协变详解
2021-10-25 08:07:54
![](https://img.aspxhome.com/file/2023/1/98261_0s.jpg)
如何使用Jenkins构建GIT+Maven项目
2021-11-18 04:42:52
![](https://img.aspxhome.com/file/2023/9/61839_0s.png)
Unity 使用TexturePacker打包图集的操作方法
2021-08-30 18:48:17
![](https://img.aspxhome.com/file/2023/4/83264_0s.jpg)
使用java采集京东商城行政区划数据示例
2023-04-17 06:31:52
如何将C语言代码转换为应用程序(也就是编译)
2022-09-02 06:30:49
SpringBoot在RequestBody中使用枚举参数案例详解
2022-12-15 05:16:30
在android中如何用Java加载解析so
2023-09-14 18:16:05
关于Springboot的日志配置
2022-12-16 10:32:33