java 文件流的處理方式 文件打包成zip
更新時(shí)間:2021年10月19日 09:52:50 作者:介寒食
這篇文章主要介紹了java 文件流的處理方式 文件打包成zip,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
java 文件流的處理 文件打包成zip
1、下載文件到本地
public void download(HttpServletResponse response){
String filePath ="";//文件路徑
String fileName ="";//文件名稱
// 讀到流中
InputStream inStream = new FileInputStream(filePath);
// 設(shè)置輸出的格式
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());
// 創(chuàng)建 FileOutputStream 對(duì)象
FileOutputStream fileOutputStream = null;
// 創(chuàng)建 ZipOutputStream
ZipOutputStream zipOutputStream = null;
try {
//創(chuàng)建文件夾
zipFile = new File(zipPath );
FileUtils.forceMkdir(zipFile);
//創(chuàng)建文件
zipFile = new File(zipFileName .toString());
if (!zipFile.exists()) {
zipFile.createNewFile();
}
// 實(shí)例化 FileOutputStream 對(duì)象
fileOutputStream = new FileOutputStream(zipFileName.toString());
// 實(shí)例化 ZipOutputStream 對(duì)象
zipOutputStream = new ZipOutputStream(fileOutputStream);
// 創(chuàng)建 ZipEntry 對(duì)象
ZipEntry zipEntry = null;
for (CL cl: ClList) {
// 實(shí)例化 ZipEntry 對(duì)象,源文件數(shù)組中的當(dāng)前文件
zipEntry = new ZipEntry(tCltjjl.getcClmc() + ".zip");
zipOutputStream.putNextEntry(zipEntry);
IOUtils.copy(new FileInputStream(cl.getcPath(), zipOutputStream);
}
} catch (Exception e) {
}finally{
//記得刪除文件
}
}
后臺(tái)多文件打包成zip返回流 前臺(tái)提供按鈕一鍵下載
項(xiàng)目pom文件添加二維碼操作,和文件打包的maven支持:
<!--二維碼相關(guān) start-->
<dependency>
<groupId>net.glxn.qrgen</groupId>
<artifactId>javase</artifactId>
<version>2.0</version>
</dependency>
<!--二維碼相關(guān) end-->
<!--文件打包相關(guān) start-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.12</version>
</dependency>
<!--文件打包相關(guān) end-->
前臺(tái)代碼:
<button type="button" onclick="downloadzip()">下載</button>
js(我用了thymeleaf模板)代碼:
<script th:inline="javascript">
function downloadzip(){
var storeType = $("#storeType").val();
if(storeType ==""){
bootAlertError("請(qǐng)選擇門店!");
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>
后臺(tái)代碼:
/**
* @Author Ni Klaus
* @Description //TODO 門店總代生成打包產(chǎn)品二維碼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);
//這里設(shè)置打包后的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("----------下載文件名編碼時(shí)出現(xiàn)錯(cuò)誤------"+e.getMessage());
}
OutputStream outputStream = response.getOutputStream();
ZipArchiveOutputStream zous = new ZipArchiveOutputStream(outputStream);
zous.setUseZip64(Zip64Mode.AsNeeded);
zous.setEncoding("utf-8");
try{
//我這里是通過(guò)不同產(chǎn)品類型生成不同產(chǎn)品的二維碼圖片流
//具體你想生成什么類型的多個(gè)文件打包,只需要循環(huán)創(chuàng)建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";
//打包文件里的每個(gè)文件的名字
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("---------------門店總代生成二維碼打包流出錯(cuò)----------------"+e.getMessage());
}finally{
if(outputStream != null){
outputStream.close();
}
if(zous != null){
zous.close();
}
}
}
最后效果:


以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot Entity中枚舉類型詳細(xì)使用介紹
本文介紹SpringBoot如何在Entity(DAO)中使用枚舉類型。(本文使用MyBatis-Plus)。在實(shí)際開發(fā)中,經(jīng)常會(huì)遇到表示類型或者狀態(tài)的情況,比如:有三種支付方式:微信、支付寶、銀聯(lián)。本文介紹如何這種場(chǎng)景的方案對(duì)比,并用實(shí)例來(lái)介紹如何用枚舉這種最優(yōu)雅的來(lái)表示2022-10-10
Java數(shù)據(jù)結(jié)構(gòu)之順序表和鏈表精解
我在學(xué)習(xí)完順序表后一直對(duì)順序表和鏈表的概念存在一些疑問(wèn),這里給出一些分析和看法,通讀本篇對(duì)大家的學(xué)習(xí)或工作具有一定的價(jià)值,需要的朋友可以參考下2021-09-09
Java關(guān)于BeabUtils.copyproperties的用法
這篇文章主要介紹了Java關(guān)于BeabUtils.copyproperties的用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
Mybatis的collection三層嵌套查詢方式(驗(yàn)證通過(guò))
這篇文章主要介紹了Mybatis的collection三層嵌套查詢方式(驗(yàn)證通過(guò)),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03

