Java?多個(gè)文件生成zip包、下載zip包的實(shí)現(xiàn)代碼
Java 多個(gè)文件生成zip包、下載zip包
一、文件上傳
代碼實(shí)現(xiàn)
/**
* 點(diǎn)擊按鈕 文件上傳
*/
@PostMapping("/uploadFile")
public String uploadFile(@RequestParam("file") MultipartFile file){
String upload = fileService.upload(file);
System.out.println("upload:"+upload);
return "上傳成功對(duì)應(yīng)路徑:"+upload;
}public String upload(MultipartFile file){
//上傳路徑
String path = "D:\\var\\file\\uploadFile"+"\\"+file.getOriginalFilename();
String fileSavePath = null;
try {
boolean upload = this.saveFileUpload(path, this.multipartFileToFile(file));
if (upload) {
fileSavePath = path;
}
} catch (Exception e) {
log.error("文件上傳失敗,", e);
}
return fileSavePath;
}
/**
*
* @param savePath 保存路徑
* @param file
* @return
*/
public boolean saveFileUpload(String savePath, File file) {
try {
if (StringUtils.isEmpty(savePath)) {
log.info("savePath is null");
return false;
}
log.info("save file path : " + savePath);
java.nio.file.Files.copy(file.toPath(), new File(savePath).toPath());
return true;
} catch (IOException e) {
log.error("saveFileUpload error", e);
}
return false;
}
/**
* MultipartFile 轉(zhuǎn) File
*/
public File multipartFileToFile(MultipartFile file) {
File toFile = null;
try{
if (file == null || StringUtils.isEmpty(file.getOriginalFilename()) || file.getSize() <= 0) {
return null;
} else {
InputStream ins;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
}catch (Exception e){
log.error("multipartFileToFile err", e);
}
return toFile;
}
/**
* 獲取文件流
*/
private void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}結(jié)果展示


二、多個(gè)文件打成zip包
代碼實(shí)現(xiàn)
@PostMapping("/yaZipFile")
public String yaZipFile() {
fileService.yaZipFile();
return "壓縮成功";
}路徑 可以從前端傳過來
public void yaZipFile() {
try {
//進(jìn)行壓縮
boolean b = FileDownloadUtils.generateFile("D:\\var\\file\\uploadFile", "zip", "D:\\var\\file", "uploadFiles");
if(b){
log.info("壓縮成功....");
File sourceFile = new File("D:\\var\\file\\uploadFile");
boolean flag = FileDownloadUtils.deleteDir(sourceFile);
if(flag){
log.info("刪除成功.....");
}
}
}catch (Exception e){
log.error("發(fā)生異常error:{}",e);
}
}
/**
* @param path 要壓縮的文件路徑
* @param format 生成的格式(zip、rar)
* @param zipPath zip的路徑
* @param zipName zip文件名
* @Description 將多個(gè)文件進(jìn)行壓縮到指定位置
*/
public static boolean generateFile(String path, String format, String zipPath, String zipName) throws Exception {
File file = new File(path);
// 壓縮文件的路徑不存在
if (!file.exists()) {
throw new Exception("路徑 " + path + " 不存在文件,無法進(jìn)行壓縮...");
}
// 用于存放壓縮文件的文件夾
String generateFile = zipPath + File.separator;
File compress = new File(generateFile);
// 如果文件夾不存在,進(jìn)行創(chuàng)建
if (!compress.exists()) {
compress.mkdirs();
}
// 目的壓縮文件
String generateFileName = compress.getAbsolutePath() + File.separator + zipName + "." + format;
// 輸出流
FileOutputStream outputStream = new FileOutputStream(generateFileName);
// 壓縮輸出流
ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(outputStream));
//壓縮
generateFile(zipOutputStream, file, "");
System.out.println("源文件位置:" + file.getAbsolutePath() + ",目的壓縮文件生成位置:" + generateFileName);
// 關(guān)閉 輸出流
zipOutputStream.close();
return true;
}
/**
* @param out 輸出流
* @param file 目標(biāo)文件
* @param dir 文件夾
* @throws Exception
*/
private static void generateFile(ZipOutputStream out, File file, String dir) throws Exception {
// 當(dāng)前的是文件夾,則進(jìn)行一步處理
if (file.isDirectory()) {
//得到文件列表信息
File[] files = file.listFiles();
//將文件夾添加到下一級(jí)打包目錄
out.putNextEntry(new ZipEntry(dir + "/"));
dir = dir.length() == 0 ? "" : dir + "/";
//循環(huán)將文件夾中的文件打包
for (int i = 0; i < files.length; i++) {
generateFile(out, files[i], dir + files[i].getName());
}
} else { // 當(dāng)前是文件
// 輸入流
FileInputStream inputStream = new FileInputStream(file);
// 標(biāo)記要打包的條目
out.putNextEntry(new ZipEntry(dir));
// 進(jìn)行寫操作
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) > 0) {
out.write(bytes, 0, len);
}
// 關(guān)閉輸入流
inputStream.close();
}
}結(jié)果展示:
壓縮包生成,把之前的目錄刪除


三、文件下載
代碼實(shí)現(xiàn)
@PostMapping("/downZipFile")
public String downZipFile(HttpServletResponse response){
fileService.downZipFile(response);
return "下載成功";
}路徑、文件名 也可以從前端傳過來
public void downZipFile(HttpServletResponse response){
String title = "uploadFiles.zip";
//壓縮文件路徑 D:\var\file
File filePath = new File("D:\\var\\file" + File.separator + title);
String filename = System.currentTimeMillis()+"_"+title;
//設(shè)置文件路徑
if (filePath.exists()) {
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
//設(shè)置下載文件類型
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment; filename=" + new String(filename.getBytes("utf-8"), "ISO8859-1"));
byte[] buffer = new byte[4096];
fis = new FileInputStream(filePath);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
// 刪除臨時(shí)文件
filePath.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}結(jié)果展示


java 批量下載將多個(gè)文件(minio中存儲(chǔ))壓縮成一個(gè)zip包
到此這篇關(guān)于Java 多個(gè)文件生成zip包、下載zip包的文章就介紹到這了,更多相關(guān)Java 多個(gè)文件生成zip包內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中關(guān)于size()>0?和isEmpt()的性能考量
這篇文章主要介紹了Java中關(guān)于size()>0?和isEmpt()性能考量,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02
Java集合與數(shù)組區(qū)別簡介及相互轉(zhuǎn)換實(shí)例
這篇文章主要介紹了Java集合與數(shù)組區(qū)別簡介及相互轉(zhuǎn)換實(shí)例,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01

