功能:支持全站分片上传

This commit is contained in:
xiaowang
2026-03-26 11:41:38 +08:00
parent 0959f14555
commit b4042b3560
18 changed files with 1324 additions and 90 deletions
@@ -1,14 +1,22 @@
package com.xiaowang.yuminailcore.controller;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.dto.ChunkUploadCompleteRequestDTO;
import com.xiaowang.yuminailcore.dto.ChunkUploadInitRequestDTO;
import com.xiaowang.yuminailcore.dto.ObjectStorageFileDTO;
import com.xiaowang.yuminailcore.service.ChunkUploadService;
import com.xiaowang.yuminailcore.service.MinioService;
import com.xiaowang.yuminailcore.service.ObjectStorageFileService;
import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO;
import com.xiaowang.yuminailcore.vo.ObjectStorageFileVO;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.FileInputStream;
import java.util.List;
import java.util.UUID;
@@ -22,10 +30,62 @@ import java.util.UUID;
@RestController
@RequestMapping("/admin/object-storage-file")
@RequiredArgsConstructor
@Validated
public class ObjectStorageFileController {
private final ObjectStorageFileService objectStorageFileService;
private final MinioService minioService;
private final ChunkUploadService chunkUploadService;
@PostMapping("/upload/init")
public Result<ChunkUploadSessionVO> initChunkUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(chunkUploadService.initAdminObjectStorageUpload(userId, requestDTO));
}
@PostMapping("/upload/chunk")
public Result<Boolean> uploadChunk(HttpServletRequest request,
@RequestParam("uploadId") String uploadId,
@RequestParam("chunkIndex") Integer chunkIndex,
@RequestParam("totalChunks") Integer totalChunks,
@RequestParam("chunk") MultipartFile chunkFile) {
Long userId = (Long) request.getAttribute("userId");
chunkUploadService.uploadAdminObjectStorageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile);
return Result.success(true);
}
@PostMapping("/upload/complete")
public Result<ObjectStorageFileVO> completeChunkUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) {
Long userId = (Long) request.getAttribute("userId");
try (ChunkUploadService.PreparedUploadFile preparedUploadFile =
chunkUploadService.prepareAdminObjectStorageFile(userId, requestDTO.getUploadId());
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
String originalFilename = preparedUploadFile.getFileName();
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = UUID.randomUUID() + fileExtension;
String fileUrl = minioService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName);
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
dto.setFileName(originalFilename);
dto.setFileUrl(fileUrl);
dto.setStatus(1);
Long fileId = objectStorageFileService.createObjectStorageFile(dto);
chunkUploadService.clearAdminObjectStorageUpload(userId, requestDTO.getUploadId());
return Result.success(objectStorageFileService.getObjectStorageFileById(fileId));
} catch (Exception e) {
e.printStackTrace();
return Result.error("文件上传失败: " + e.getMessage());
}
}
@DeleteMapping("/upload/{uploadId}")
public Result<Boolean> cancelChunkUpload(HttpServletRequest request, @PathVariable String uploadId) {
Long userId = (Long) request.getAttribute("userId");
chunkUploadService.clearAdminObjectStorageUpload(userId, uploadId);
return Result.success(true);
}
/**
* 上传文件
@@ -160,4 +220,4 @@ public class ObjectStorageFileController {
List<ObjectStorageFileVO> objectStorageFileVOs = objectStorageFileService.listObjectStorageFilesByStatus(status);
return Result.success(objectStorageFileVOs);
}
}
}
@@ -5,7 +5,9 @@ import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.dto.*;
import com.xiaowang.yuminailcore.entity.UserDO;
import com.xiaowang.yuminailcore.mapper.UserMapper;
import com.xiaowang.yuminailcore.service.ChunkUploadService;
import com.xiaowang.yuminailcore.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO;
import com.xiaowang.yuminailcore.vo.LoginShopSelectionVO;
import com.xiaowang.yuminailcore.vo.LoginResponseVO;
import com.xiaowang.yuminailcore.vo.UserVO;
@@ -20,6 +22,7 @@ import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.validation.Valid;
import javax.servlet.http.HttpServletRequest;
import java.io.FileInputStream;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
@@ -38,6 +41,7 @@ public class UserController {
private final UserService userService;
private final MinioService minioService;
private final ChunkUploadService chunkUploadService;
private final VerificationCodeService verificationCodeService;
private final UserMapper userMapper;
private final AdminScopeHelper adminScopeHelper;
@@ -381,6 +385,50 @@ public class UserController {
* @param file 头像文件
* @return 头像URL
*/
@PostMapping("/upload-avatar/init")
public Result<ChunkUploadSessionVO> initAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(chunkUploadService.initUserAvatarUpload(userId, requestDTO));
}
@PostMapping("/upload-avatar/chunk")
public Result<Boolean> uploadAvatarChunk(HttpServletRequest request,
@RequestParam("uploadId") String uploadId,
@RequestParam("chunkIndex") Integer chunkIndex,
@RequestParam("totalChunks") Integer totalChunks,
@RequestParam("chunk") MultipartFile chunkFile) {
Long userId = (Long) request.getAttribute("userId");
chunkUploadService.uploadUserAvatarChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile);
return Result.success(true);
}
@PostMapping("/upload-avatar/complete")
public Result<String> completeAvatarUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) {
Long userId = (Long) request.getAttribute("userId");
try (ChunkUploadService.PreparedUploadFile preparedUploadFile =
chunkUploadService.prepareUserAvatarFile(userId, requestDTO.getUploadId());
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
String originalFilename = preparedUploadFile.getFileName();
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = "avatar/" + userId + "/" + UUID.randomUUID() + fileExtension;
String avatarUrl = minioService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName);
userService.updateUserAvatar(userId, avatarUrl);
chunkUploadService.clearUserAvatarUpload(userId, requestDTO.getUploadId());
return Result.success(avatarUrl);
} catch (Exception e) {
e.printStackTrace();
return Result.error("头像上传失败: " + e.getMessage());
}
}
@DeleteMapping("/upload-avatar/{uploadId}")
public Result<Boolean> cancelAvatarUpload(HttpServletRequest request, @PathVariable String uploadId) {
Long userId = (Long) request.getAttribute("userId");
chunkUploadService.clearUserAvatarUpload(userId, uploadId);
return Result.success(true);
}
@PostMapping("/upload-avatar")
public Result<String> uploadAvatar(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
try {
@@ -0,0 +1,15 @@
package com.xiaowang.yuminailcore.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
/**
* 分片上传完成请求
*/
@Data
public class ChunkUploadCompleteRequestDTO {
@NotBlank(message = "上传标识不能为空")
private String uploadId;
}
@@ -0,0 +1,30 @@
package com.xiaowang.yuminailcore.dto;
import lombok.Data;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* 分片上传初始化请求
*/
@Data
public class ChunkUploadInitRequestDTO {
@NotBlank(message = "文件名不能为空")
private String fileName;
@NotNull(message = "文件大小不能为空")
@Min(value = 1, message = "文件大小不合法")
private Long fileSize;
@NotBlank(message = "文件类型不能为空")
private String contentType;
@NotBlank(message = "文件指纹不能为空")
private String fileFingerprint;
@NotBlank(message = "上传场景不能为空")
private String scene;
}
@@ -0,0 +1,40 @@
package com.xiaowang.yuminailcore.service;
import com.xiaowang.yuminailcore.dto.ChunkUploadInitRequestDTO;
import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
public interface ChunkUploadService {
ChunkUploadSessionVO initAdminObjectStorageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO);
ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO);
void uploadAdminObjectStorageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile);
void uploadUserAvatarChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile);
PreparedUploadFile prepareAdminObjectStorageFile(Long ownerId, String uploadId);
PreparedUploadFile prepareUserAvatarFile(Long ownerId, String uploadId);
void clearAdminObjectStorageUpload(Long ownerId, String uploadId);
void clearUserAvatarUpload(Long ownerId, String uploadId);
interface PreparedUploadFile extends AutoCloseable {
File getFile();
String getFileName();
String getContentType();
long getFileSize();
@Override
void close();
}
}
@@ -7,6 +7,8 @@ public interface MinioService {
String uploadFile(MultipartFile file, String objectName) throws Exception;
String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception;
InputStream downloadFile(String objectName) throws Exception;
void deleteFile(String objectName) throws Exception;
@@ -0,0 +1,404 @@
package com.xiaowang.yuminailcore.service.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.yuminailcore.dto.ChunkUploadInitRequestDTO;
import com.xiaowang.yuminailcore.service.ChunkUploadService;
import com.xiaowang.yuminailcore.vo.ChunkUploadSessionVO;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
@Slf4j
@Service
@RequiredArgsConstructor
public class ChunkUploadServiceImpl implements ChunkUploadService {
private static final int CHUNK_SIZE = 1024 * 1024;
private static final long SESSION_EXPIRE_HOURS = 24;
private static final String METADATA_FILE_NAME = "metadata.json";
private static final String CHUNK_FILE_PREFIX = "chunk-";
private static final String CHUNK_FILE_SUFFIX = ".part";
private final ObjectMapper objectMapper;
@Override
public ChunkUploadSessionVO initAdminObjectStorageUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) {
return initUpload(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, requestDTO);
}
@Override
public ChunkUploadSessionVO initUserAvatarUpload(Long ownerId, ChunkUploadInitRequestDTO requestDTO) {
return initUpload(UploadTargetType.USER_AVATAR, ownerId, requestDTO);
}
@Override
public void uploadAdminObjectStorageChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) {
uploadChunk(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId, chunkIndex, totalChunks, chunkFile);
}
@Override
public void uploadUserAvatarChunk(Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) {
uploadChunk(UploadTargetType.USER_AVATAR, ownerId, uploadId, chunkIndex, totalChunks, chunkFile);
}
@Override
public PreparedUploadFile prepareAdminObjectStorageFile(Long ownerId, String uploadId) {
return prepareMergedFile(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId);
}
@Override
public PreparedUploadFile prepareUserAvatarFile(Long ownerId, String uploadId) {
return prepareMergedFile(UploadTargetType.USER_AVATAR, ownerId, uploadId);
}
@Override
public void clearAdminObjectStorageUpload(Long ownerId, String uploadId) {
clearUpload(UploadTargetType.ADMIN_OBJECT_STORAGE, ownerId, uploadId);
}
@Override
public void clearUserAvatarUpload(Long ownerId, String uploadId) {
clearUpload(UploadTargetType.USER_AVATAR, ownerId, uploadId);
}
private ChunkUploadSessionVO initUpload(UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO) {
validateInitRequest(ownerId, requestDTO);
cleanupExpiredSessionsQuietly();
String uploadId = buildUploadId(targetType, ownerId, requestDTO);
Path sessionDir = getSessionDir(uploadId);
int totalChunks = (int) Math.ceil((double) requestDTO.getFileSize() / CHUNK_SIZE);
try {
Files.createDirectories(sessionDir);
UploadMetadata metadata = readMetadataIfExists(sessionDir);
if (metadata != null && !isCompatible(metadata, targetType, ownerId, requestDTO, totalChunks)) {
deleteDirectory(sessionDir);
Files.createDirectories(sessionDir);
metadata = null;
}
if (metadata == null) {
metadata = new UploadMetadata();
metadata.setUploadId(uploadId);
metadata.setTargetType(targetType.name());
metadata.setOwnerId(ownerId);
metadata.setFileName(requestDTO.getFileName());
metadata.setContentType(requestDTO.getContentType());
metadata.setFileSize(requestDTO.getFileSize());
metadata.setFileFingerprint(requestDTO.getFileFingerprint());
metadata.setScene(requestDTO.getScene());
metadata.setChunkSize(CHUNK_SIZE);
metadata.setTotalChunks(totalChunks);
metadata.setCreatedAt(Instant.now().toEpochMilli());
}
metadata.setUpdatedAt(Instant.now().toEpochMilli());
writeMetadata(sessionDir, metadata);
ChunkUploadSessionVO sessionVO = new ChunkUploadSessionVO();
sessionVO.setUploadId(uploadId);
sessionVO.setChunkSize(metadata.getChunkSize());
sessionVO.setTotalChunks(metadata.getTotalChunks());
sessionVO.setUploadedChunks(getUploadedChunks(sessionDir, metadata.getTotalChunks()));
return sessionVO;
} catch (IOException e) {
log.error("初始化分片上传失败, uploadId={}", uploadId, e);
throw new RuntimeException("初始化上传失败");
}
}
private void uploadChunk(UploadTargetType targetType, Long ownerId, String uploadId, Integer chunkIndex, Integer totalChunks, MultipartFile chunkFile) {
if (ownerId == null) {
throw new RuntimeException("未获取到上传用户信息");
}
if (!StringUtils.hasText(uploadId)) {
throw new RuntimeException("上传标识不能为空");
}
if (chunkIndex == null || chunkIndex < 0) {
throw new RuntimeException("分片序号不合法");
}
if (totalChunks == null || totalChunks <= 0) {
throw new RuntimeException("分片总数不合法");
}
if (chunkFile == null || chunkFile.isEmpty()) {
throw new RuntimeException("上传分片不能为空");
}
Path sessionDir = getSessionDir(uploadId);
UploadMetadata metadata = readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId);
if (!Objects.equals(metadata.getTotalChunks(), totalChunks)) {
throw new RuntimeException("分片总数不匹配,请重新上传");
}
if (chunkIndex >= metadata.getTotalChunks()) {
throw new RuntimeException("分片序号超出范围");
}
try {
Path chunkPath = getChunkPath(sessionDir, chunkIndex);
Path tempChunkPath = sessionDir.resolve(chunkPath.getFileName().toString() + ".tmp");
try (InputStream inputStream = chunkFile.getInputStream()) {
Files.copy(inputStream, tempChunkPath, StandardCopyOption.REPLACE_EXISTING);
}
Files.move(tempChunkPath, chunkPath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
metadata.setUpdatedAt(Instant.now().toEpochMilli());
writeMetadata(sessionDir, metadata);
} catch (IOException e) {
log.error("保存分片失败, uploadId={}, chunkIndex={}", uploadId, chunkIndex, e);
throw new RuntimeException("上传分片失败");
}
}
private PreparedUploadFile prepareMergedFile(UploadTargetType targetType, Long ownerId, String uploadId) {
Path sessionDir = getSessionDir(uploadId);
UploadMetadata metadata = readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId);
List<Integer> uploadedChunks = getUploadedChunks(sessionDir, metadata.getTotalChunks());
if (uploadedChunks.size() != metadata.getTotalChunks()) {
throw new RuntimeException("文件尚未上传完成,请稍后再试");
}
try {
Path mergedFilePath = Files.createTempFile("yuminail-upload-", ".tmp");
try (OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(mergedFilePath))) {
for (int chunkIndex = 0; chunkIndex < metadata.getTotalChunks(); chunkIndex++) {
Path chunkPath = getChunkPath(sessionDir, chunkIndex);
if (!Files.exists(chunkPath)) {
throw new RuntimeException("缺少上传分片,请重新上传");
}
Files.copy(chunkPath, outputStream);
}
}
return new LocalPreparedUploadFile(mergedFilePath.toFile(), metadata.getFileName(), metadata.getContentType(), metadata.getFileSize());
} catch (IOException e) {
log.error("合并上传文件失败, uploadId={}", uploadId, e);
throw new RuntimeException("合并上传文件失败");
}
}
private void clearUpload(UploadTargetType targetType, Long ownerId, String uploadId) {
Path sessionDir = getSessionDir(uploadId);
readAndValidateMetadata(sessionDir, targetType, ownerId, uploadId);
deleteDirectory(sessionDir);
}
private UploadMetadata readAndValidateMetadata(Path sessionDir, UploadTargetType targetType, Long ownerId, String uploadId) {
UploadMetadata metadata = readMetadataIfExists(sessionDir);
if (metadata == null) {
throw new RuntimeException("上传会话不存在,请重新上传");
}
if (!targetType.name().equals(metadata.getTargetType()) || !Objects.equals(ownerId, metadata.getOwnerId())) {
throw new RuntimeException("无权操作该上传会话");
}
if (!uploadId.equals(metadata.getUploadId())) {
throw new RuntimeException("上传会话不匹配");
}
return metadata;
}
private void validateInitRequest(Long ownerId, ChunkUploadInitRequestDTO requestDTO) {
if (ownerId == null) {
throw new RuntimeException("未获取到上传用户信息");
}
if (requestDTO == null) {
throw new RuntimeException("上传参数不能为空");
}
if (!StringUtils.hasText(requestDTO.getFileName())) {
throw new RuntimeException("文件名不能为空");
}
if (!StringUtils.hasText(requestDTO.getContentType())) {
throw new RuntimeException("文件类型不能为空");
}
if (!StringUtils.hasText(requestDTO.getFileFingerprint())) {
throw new RuntimeException("文件指纹不能为空");
}
if (!StringUtils.hasText(requestDTO.getScene())) {
throw new RuntimeException("上传场景不能为空");
}
if (requestDTO.getFileSize() == null || requestDTO.getFileSize() <= 0) {
throw new RuntimeException("文件大小不合法");
}
}
private boolean isCompatible(UploadMetadata metadata, UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO, int totalChunks) {
return targetType.name().equals(metadata.getTargetType())
&& Objects.equals(ownerId, metadata.getOwnerId())
&& Objects.equals(metadata.getFileSize(), requestDTO.getFileSize())
&& Objects.equals(metadata.getTotalChunks(), totalChunks)
&& Objects.equals(metadata.getFileFingerprint(), requestDTO.getFileFingerprint())
&& Objects.equals(metadata.getScene(), requestDTO.getScene());
}
private String buildUploadId(UploadTargetType targetType, Long ownerId, ChunkUploadInitRequestDTO requestDTO) {
String raw = targetType.name() + "|" + ownerId + "|" + requestDTO.getScene() + "|" + requestDTO.getFileFingerprint();
return DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8));
}
private Path getSessionDir(String uploadId) {
return getUploadRoot().resolve(uploadId);
}
private Path getUploadRoot() {
return Path.of(System.getProperty("java.io.tmpdir"), "yuminail", "chunk-upload");
}
private Path getChunkPath(Path sessionDir, int chunkIndex) {
return sessionDir.resolve(CHUNK_FILE_PREFIX + String.format("%05d", chunkIndex) + CHUNK_FILE_SUFFIX);
}
private UploadMetadata readMetadataIfExists(Path sessionDir) {
Path metadataPath = sessionDir.resolve(METADATA_FILE_NAME);
if (!Files.exists(metadataPath)) {
return null;
}
try {
return objectMapper.readValue(metadataPath.toFile(), UploadMetadata.class);
} catch (IOException e) {
log.warn("读取上传元数据失败: {}", metadataPath, e);
return null;
}
}
private void writeMetadata(Path sessionDir, UploadMetadata metadata) throws IOException {
Path metadataPath = sessionDir.resolve(METADATA_FILE_NAME);
objectMapper.writeValue(metadataPath.toFile(), metadata);
}
private List<Integer> getUploadedChunks(Path sessionDir, int totalChunks) {
List<Integer> uploadedChunks = new ArrayList<>();
for (int chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) {
if (Files.exists(getChunkPath(sessionDir, chunkIndex))) {
uploadedChunks.add(chunkIndex);
}
}
return uploadedChunks;
}
private void cleanupExpiredSessionsQuietly() {
try {
Path uploadRoot = getUploadRoot();
if (!Files.exists(uploadRoot)) {
return;
}
Instant expireAt = Instant.now().minus(SESSION_EXPIRE_HOURS, ChronoUnit.HOURS);
try (var stream = Files.list(uploadRoot)) {
stream.filter(Files::isDirectory)
.sorted(Comparator.comparing(Path::toString))
.forEach(sessionDir -> cleanupExpiredSession(sessionDir, expireAt));
}
} catch (IOException e) {
log.warn("清理过期上传会话失败", e);
}
}
private void cleanupExpiredSession(Path sessionDir, Instant expireAt) {
UploadMetadata metadata = readMetadataIfExists(sessionDir);
if (metadata == null) {
deleteDirectory(sessionDir);
return;
}
Instant updatedAt = Instant.ofEpochMilli(metadata.getUpdatedAt() == null ? 0L : metadata.getUpdatedAt());
if (updatedAt.isBefore(expireAt)) {
deleteDirectory(sessionDir);
}
}
private void deleteDirectory(Path directory) {
if (directory == null || !Files.exists(directory)) {
return;
}
try (var walk = Files.walk(directory)) {
walk.sorted(Comparator.reverseOrder()).forEach(path -> {
try {
Files.deleteIfExists(path);
} catch (IOException e) {
log.warn("删除上传临时文件失败: {}", path, e);
}
});
} catch (IOException e) {
log.warn("删除上传目录失败: {}", directory, e);
}
}
private enum UploadTargetType {
ADMIN_OBJECT_STORAGE,
USER_AVATAR
}
@Data
private static class UploadMetadata {
private String uploadId;
private String targetType;
private Long ownerId;
private String fileName;
private String contentType;
private Long fileSize;
private String fileFingerprint;
private String scene;
private Integer chunkSize;
private Integer totalChunks;
private Long createdAt;
private Long updatedAt;
}
private static class LocalPreparedUploadFile implements PreparedUploadFile {
private final File file;
private final String fileName;
private final String contentType;
private final long fileSize;
private LocalPreparedUploadFile(File file, String fileName, String contentType, long fileSize) {
this.file = file;
this.fileName = fileName;
this.contentType = contentType;
this.fileSize = fileSize;
}
@Override
public File getFile() {
return file;
}
@Override
public String getFileName() {
return fileName;
}
@Override
public String getContentType() {
return contentType;
}
@Override
public long getFileSize() {
return fileSize;
}
@Override
public void close() {
if (file != null && file.exists() && !file.delete()) {
log.warn("删除合并后的临时文件失败: {}", file.getAbsolutePath());
}
}
}
}
@@ -24,10 +24,18 @@ public class MinioServiceImpl implements MinioService {
@Override
public String uploadFile(MultipartFile file, String objectName) throws Exception {
try {
InputStream inputStream = file.getInputStream();
long fileSize = file.getSize();
String contentType = file.getContentType();
try (InputStream inputStream = file.getInputStream()) {
return uploadStream(inputStream, file.getSize(), file.getContentType(), objectName);
}
} catch (Exception e) {
log.error("文件上传失败: {}", objectName, e);
throw e;
}
}
@Override
public String uploadStream(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception {
try {
minioClient.putObject(
PutObjectArgs.builder()
.bucket(minioConfig.getBucketName())
@@ -0,0 +1,20 @@
package com.xiaowang.yuminailcore.vo;
import lombok.Data;
import java.util.List;
/**
* 分片上传会话信息
*/
@Data
public class ChunkUploadSessionVO {
private String uploadId;
private Integer chunkSize;
private Integer totalChunks;
private List<Integer> uploadedChunks;
}