利用Python實現壓縮一個文件夾 二、知識點 文件讀寫 基礎語法 字元串處理 迴圈遍歷 文件壓縮 三、代碼解析 導入系統包 import platform import os import zipfile # 我還給大家準備了這些資料:Python視頻教程、100本Python電子書、基礎、爬蟲、 ...
文件上傳工具--FileUtil
package com.youmejava.chun.util;
import lombok.Data;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* 文件工具
*/
@Data
public class FileUtil {
private List<File> filelist;//文件列表
private String strPath;//路徑
public FileUtil() {
}
public FileUtil(List<File> filelist, String strPath) {
this.filelist = filelist;
this.strPath = strPath;
getFileList(this.strPath);
}
/**
* 獲取文件列表
* @param strPath
* @return
*/
public List<File> getFileList(String strPath) {
File dir = new File(strPath);
File[] files = dir.listFiles(); // 該文件目錄下文件全部放入數組
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
if (files[i].isDirectory()) { // 判斷是文件還是文件夾
getFileList(files[i].getAbsolutePath()); // 獲取文件絕對路徑
} else { // 判斷文件名
String strFileName = files[i].getAbsolutePath();
// System.out.println("---" + strFileName);
filelist.add(files[i]);
}
}
}
return filelist;
}
/**
* 合併文件
* @param from
* @param to
* @throws IOException
*/
public static void mergeFile(String from, String to) throws IOException {
File t = new File(to);
FileInputStream in = null;
FileChannel inChannel = null;
System.out.println("t "+t);
FileOutputStream out = new FileOutputStream(t,true);
FileChannel outChannel = out.getChannel();
File f = new File(from);
System.out.println("f "+f.isDirectory());
// 獲取目錄下的每一個文件名,再將每個文件一次寫入目標文件
if (f.isDirectory()) {
List<File> list = getAllFileAndSort(from);
System.out.println("sortlist "+list);
// 記錄新文件最後一個數據的位置
long start = 0;
for (File file : list) {
in = new FileInputStream(file);
inChannel = in.getChannel();
// 從inChannel中讀取file.length()長度的數據,寫入outChannel的start處
outChannel.transferFrom(inChannel, start, file.length());
start += file.length();
in.close();
inChannel.close();
}
}
out.close();
outChannel.close();
}
/**
* 所有文件排序
* @param dirPath 文件根目錄路徑
* @return
*/
public static List<File> getAllFileAndSort(String dirPath) {
File dirFile = new File(dirPath);
File[] listFiles = dirFile.listFiles();
List<File> list = Arrays.asList(listFiles);
Collections.sort(list, (o1, o2) -> {
String _str=o1.getName().split("\\.")[0];
String _num=_str.split("_")[1];
String _str2=o2.getName().split("\\.")[0];
String _num2=_str2.split("_")[1];
return Integer.parseInt(_num) - Integer.parseInt(_num2);
});
return list;
}
/**
* 刪除文件夾
* 刪除文件夾需要把包含的文件及文件夾先刪除,才能成功
* https://blog.csdn.net/m0_57640408/article/details/120774050
* @param directory 文件夾名
* @return 刪除成功返回true,失敗返回false
*/
public static boolean deleteDirectory(String directory) {
// directory不以文件分隔符(/或\)結尾時,自動添加文件分隔符,不同系統下File.separator方法會自動添加相應的分隔符
if (!directory.endsWith(File.separator)) {
directory = directory + File.separator;
}
File directoryFile = new File(directory);
// 判斷directory對應的文件是否存在,或者是否是一個文件夾
if (!directoryFile.exists() || !directoryFile.isDirectory()) {
System.out.println("文件夾刪除失敗,文件夾不存在" + directory);
return false;
}
boolean flag = true;
// 刪除文件夾下的所有文件和文件夾
File[] files = directoryFile.listFiles();
for (int i = 0; i < files.length; i++) { // 迴圈刪除所有的子文件及子文件夾
// 刪除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag) {
break;
}
} else { // 刪除子文件夾
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag) {
break;
}
}
}
if (!flag) {
System.out.println("刪除失敗");
return false;
}
// 最後刪除當前文件夾
if (directoryFile.delete()) {
System.out.println("刪除成功:" + directory);
return true;
} else {
System.out.println("刪除失敗:" + directory);
return false;
}
}
/**
* 刪除文件
*
* @param fileName 文件名
* @return 刪除成功返回true,失敗返回false
*/
public static boolean deleteFile(String fileName) {
File file = new File(fileName);
if (file.isFile() && file.exists()) {
file.delete();
System.out.println("刪除文件成功:" + fileName);
return true;
} else {
System.out.println("刪除文件失敗:" + fileName);
return false;
}
}
}
分片上傳文件介面
package com.youmejava.chun.commoninterface;
import com.youmejava.chun.util.FileUtil;
import com.youmejava.chun.util.ResultVo;
import com.youmejava.chun.util.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/api/apiSystem/upload")
@Api(value = "文件上傳", tags = "文件上傳")
public class UploadController {
@Value("${filePath1}")
private String filePath;
@PostMapping("/register")
@ApiOperation(value = "文件註冊", notes = "文件註冊")
@ApiImplicitParams({@ApiImplicitParam(value = "哈希值", name = "hash", required = true, paramType = "body")})
public ResultVo register(@RequestBody Map<String, Object> map) {
System.out.println("hash: " + map.get("hash"));
if (!StringUtil.isNotBlankAndNull(map.get("hash").toString())) {
// return ResultVo.failure("哈希值不可為空");
throw new ExpiredCredentialsException("哈希值不可為空!");
}
String _filePath=filePath;
if (!_filePath.endsWith("/")) {
_filePath+="/";
}
// String _pathStr = "C:\\Users\\JH-rent\\Desktop\\java啟動文件\\test" + "\\" + map.get("hash");
String _pathStr=_filePath+map.get("hash");
//創建不同的文件夾目錄
File file = new File(_pathStr);
//判斷文件夾是否存在
if (!file.exists()) {
//如果文件夾不存在,則創建新的的文件夾
file.mkdirs();
}
File f = new File(_pathStr);
// 檢查目錄是否已上傳過文件,如果上傳過,返回上傳個數
if (f.isDirectory()) {
File dirFile = new File(_pathStr);
File[] listFiles = dirFile.listFiles();
List<File> list = Arrays.asList(listFiles);
if (list == null&&list.size()>0) {
Map<String, Object>map1=new HashMap<>();
map1.put("number",list.size());
return ResultVo.success(map1);
}
}
return ResultVo.success();
}
@PostMapping("/uploadFile")
@ResponseBody
@ApiOperation(value = "上傳文件", notes = "上傳文件")
@ApiImplicitParams({@ApiImplicitParam(value = "哈希值", name = "hash", required = true, paramType = "body"), @ApiImplicitParam(value = "文件流", name = "file", required = true, paramType = "body"), @ApiImplicitParam(value = "文件名稱", name = "fileName", required = true, paramType = "body"),})
public ResultVo uploadFile(HttpServletRequest request) {
MultipartHttpServletRequest params = ((MultipartHttpServletRequest) request);
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
String _fileName = params.getParameter("fileName");
String _hash = params.getParameter("hash");
if (!StringUtil.isNotBlankAndNull(_hash)) {
throw new ExpiredCredentialsException("哈希值不可為空!");
}
if (!StringUtil.isNotBlankAndNull(_fileName)) {
throw new ExpiredCredentialsException("文件名稱不可為空!");
}
// System.out.println("_fileName: " + _fileName);
// System.out.println("_hash: " + _hash);
// System.out.println("files: " + files);
// System.out.println(params.getParameter("file"));
// String _pathStr = "C:\\Users\\JH-rent\\Desktop\\java啟動文件\\test" + "\\" + _hash + "\\";
String _filePath=filePath;
if (!_filePath.endsWith("/")) {
_filePath+="/";
}
String _pathStr =_filePath+_hash+"/";
FileOutputStream fileOut = null;
//寫入到文件(註意文件保存路徑的後面一定要加上文件的名稱)
try {
fileOut = new FileOutputStream(_pathStr + _fileName);
BufferedOutputStream bos = new BufferedOutputStream(fileOut);
BufferedInputStream bis = null;
for (MultipartFile file : files) {
// file.transferTo(new File(_pathStr + file.getOriginalFilename()));
// System.out.println(file.getInputStream());
bis = new BufferedInputStream(file.getInputStream());
}
byte[] buf = new byte[4096];
int length = bis.read(buf);
//保存文件
while (length != -1) {
bos.write(buf, 0, length);
length = bis.read(buf);
}
bos.close();
bis.close();
return ResultVo.success();
} catch (Exception e) {
e.printStackTrace();
return ResultVo.failure(e.getMessage());
}
}
@GetMapping("/getMergeFile")
@ApiOperation(value = "獲取合併文件", notes = "獲取合併文件")
@ApiImplicitParams({@ApiImplicitParam(value = "哈希值", name = "hash", required = true, dataType = "String"), @ApiImplicitParam(value = "文件名稱", name = "fileName", required = true, dataType = "String")})
public ResultVo getMergeFile(@RequestParam(value = "hash") String hash, @RequestParam(value = "fileName") String fileName) {
// String _pathStr = "C:\\Users\\JH-rent\\Desktop\\java啟動文件\\test" + "\\" + hash + "\\";
// String _pathStr1 = "C:\\Users\\JH-rent\\Desktop\\java啟動文件\\test";
String _filePath=filePath;
if (!_filePath.endsWith("/")) {
_filePath+="/";
}
String _pathStr = _filePath + hash + "/";
String _pathStr1 = _filePath;
try {
// if (!_pathStr1.endsWith("\\")) {
// _pathStr1 += "\\";
// }
_pathStr1 += fileName;
FileUtil.mergeFile(_pathStr, _pathStr1);
//合併成功刪除加密文件
FileUtil.deleteDirectory(_pathStr);
} catch (IOException e) {
e.printStackTrace();
}
Map<String, Object>map=new HashMap<>();
map.put("fileUrl",_pathStr1);
return ResultVo.success(map);
}
}
前端分片鏈接:https://www.cnblogs.com/wxchun/p/15892243.html