1. 程式人生 > 其它 >讀取網路圖片url,並打包生成zip,上傳到伺服器某個目錄

讀取網路圖片url,並打包生成zip,上傳到伺服器某個目錄

package com.yft.util;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
* @Author wjx
* @Date 2022/3/16
*/
@Slf4j
public class FileZipUtils {
public static void main(String[] args) throws Exception {
String img1 = "網路圖片url";
String img2 = "網路圖片url";
String fileStr = "D:\\image\\";


for (int i = 0; i < 2; i++) {
String zipFileStr = "D:\\imageZip\\壓縮包" + i + ".zip";

List<Map<String, String>> imageUrls = new ArrayList<>();
Map<String, String> imageUrl = new HashMap<>();
imageUrl.put("圖片1", img1);
imageUrl.put("圖片2", img2);
imageUrls.add(imageUrl);
FileZipUtils.FileMain(imageUrls,fileStr,zipFileStr);
}

//

}

public static void FileMain(List<Map<String, String>> imageUrls,String fileStr,String zipFileStr) throws Exception{
try {
// 建立一個資料夾
File file = new File(fileStr);
file.mkdirs();
//多個圖片下載地址
for(int i=0;i<imageUrls.size();i++) {
Map<String, String> img = imageUrls.get(i);
for (Map.Entry<String, String> stringStringEntry : img.entrySet()) {
String fileName = stringStringEntry.getKey();
String fileUrl = stringStringEntry.getValue();
//new一個URL物件
URL url = new URL(fileUrl);
//開啟連結
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//設定請求方式為"GET"
conn.setRequestMethod("GET");
//超時響應時間為10秒
conn.setConnectTimeout(10 * 1000);
//通過輸入流獲取圖片資料
InputStream inStream = conn.getInputStream();
//得到圖片的二進位制資料,以二進位制封裝得到資料,具有通用性
byte[] data = readInputStream(inStream);
//new一個檔案物件用來儲存圖片,預設儲存當前工程根目錄
File imageFile = new File(fileStr + fileName + ".png");
//建立輸出流
FileOutputStream outStream = new FileOutputStream(imageFile);
//寫入資料
outStream.write(data);
//關閉輸出流
outStream.close();
}

}

// 壓縮法
FileOutputStream fos1 = new FileOutputStream(new File(zipFileStr));
FileZipUtils.toZip1(fileStr, fos1,false);

// 刪除檔案和壓縮檔案
FileZipUtils.delFolder(fileStr);
//FileUtil.delFolder(zipFileStr);

} catch (MalformedURLException e) {
log.warn("圖片url格式錯誤:", e);
} catch (IOException e) {
log.warn("圖片沒找到:", e);
}
}

/**
* 遞迴壓縮方法
* @param sourceFile 原始檔
* @param zos zip輸出流
* @param name 壓縮後的名稱
* @param KeepDirStructure 是否保留原來的目錄結構,true:保留目錄結構;
* false:所有檔案跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名檔案,會壓縮失敗)
* @throws Exception
*/
private static void compress(File sourceFile, ZipOutputStream zos, String name,
boolean KeepDirStructure) throws Exception{
byte[] buf = new byte[2 * 1024];
if(sourceFile.isFile()){
// 向zip輸出流中新增一個zip實體,構造器中name為zip實體的檔案的名字
zos.putNextEntry(new ZipEntry(name));
// copy檔案到zip輸出流中
int len;
FileInputStream in = new FileInputStream(sourceFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
// Complete the entry
zos.closeEntry();
in.close();
} else {
File[] listFiles = sourceFile.listFiles();
if(listFiles == null || listFiles.length == 0){
// 需要保留原來的檔案結構時,需要對空資料夾進行處理
if(KeepDirStructure){
// 空資料夾的處理
zos.putNextEntry(new ZipEntry(name + "/"));
// 沒有檔案,不需要檔案的copy
zos.closeEntry();
}
}else {
for (File file : listFiles) {
// 判斷是否需要保留原來的檔案結構
if (KeepDirStructure) {
// 注意:file.getName()前面需要帶上父資料夾的名字加一斜槓,
// 不然最後壓縮包中就不能保留原來的檔案結構,即:所有檔案都跑到壓縮包根目錄下了
compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
} else {
compress(file, zos, file.getName(),KeepDirStructure);
}
}
}
}
}

/**
* 壓縮成ZIP 方法1
* @param srcDir 壓縮資料夾路徑
* @param out 壓縮檔案輸出流
* @param KeepDirStructure 是否保留原來的目錄結構,true:保留目錄結構;
* false:所有檔案跑到壓縮包根目錄下(注意:不保留目錄結構可能會出現同名檔案,會壓縮失敗)
* @throws RuntimeException 壓縮失敗會丟擲執行時異常
*/
public static void toZip1(String srcDir, OutputStream out, boolean KeepDirStructure)
throws RuntimeException{
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
File sourceFile = new File(srcDir);
compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
long end = System.currentTimeMillis();
System.out.println("壓縮完成,耗時:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* 壓縮成ZIP 方法2
* @param srcFiles 需要壓縮的檔案列表
* @param out 壓縮檔案輸出流
* @throws RuntimeException 壓縮失敗會丟擲執行時異常
*/
public static void toZip2(List<File> srcFiles , OutputStream out)throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[2 * 1024];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("壓縮完成,耗時:" + (end - start) +" ms");
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

/**
* 得到圖片的二進位制資料,以二進位制封裝得到資料,具有通用性
* @param inStream
* @return
* @throws Exception
*/
public static byte[] readInputStream(InputStream inStream) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
//建立一個Buffer字串
byte[] buffer = new byte[1024];
//每次讀取的字串長度,如果為-1,代表全部讀取完畢
int len = 0;
//使用一個輸入流從buffer裡把資料讀取出來
while( (len=inStream.read(buffer)) != -1 ){
//用輸出流往buffer裡寫入資料,中間引數代表從哪個位置開始讀,len代表讀取的長度
outStream.write(buffer, 0, len);
}
//關閉輸入流
inStream.close();
//把outStream裡的資料寫入記憶體
return outStream.toByteArray();
}

/**
* 刪除資料夾
* @param folderPath 資料夾完整絕對路徑
* @return
*/
public static void delFolder(String folderPath) {
try {
delAllFile(folderPath); //刪除完裡面所有內容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
myFilePath.delete(); //刪除空資料夾
}
catch (Exception e) {
}
}


/**
* 刪除指定資料夾下所有檔案
* @param path 資料夾完整絕對路徑
* @return
* @return
*/
public static boolean delAllFile(String path) {
boolean bea = false;
File file = new File(path);
if (!file.exists()) {
return bea;
}
if (!file.isDirectory()) {
return bea;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
}else{
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFile(path+"/"+ tempList[i]);//先刪除資料夾裡面的檔案
delFolder(path+"/"+ tempList[i]);//再刪除空資料夾
bea = true;
}
}
return bea;
}
}