Files
aida-seller/src/main/java/com/aida/seller/module/file/FileUploadController.java
2026-04-27 11:47:17 +08:00

88 lines
3.2 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.aida.seller.module.file;
import cn.hutool.crypto.digest.DigestUtil;
import com.aida.seller.common.constants.CommonConstants;
import com.aida.seller.common.context.UserContext;
import com.aida.seller.common.exception.BusinessException;
import com.aida.seller.common.result.Response;
import com.aida.seller.util.MinioUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Arrays;
/**
* 文件上传控制器
*
* @author Fida Team
* @date 2026-02-03
*/
@Slf4j
@RestController
@RequestMapping("/file")
@Tag(name = "文件管理", description = "文件上传、下载等功能接口")
@RequiredArgsConstructor
public class FileUploadController {
private final MinioUtil minioUtil;
@Value("${multipart.max-file-size}")
private Long maxFileSize;
@PostMapping("/upload")
@Operation(summary = "文件上传", description = "上传文件到Minio服务器")
public Response<String> uploadFile(
@Parameter(description = "文件", required = true) @RequestParam("file") MultipartFile file,
@Parameter(description = "允许的文件类型") @RequestParam(value = "allowedTypes", required = false) String[] allowedTypes
) {
Long userId = UserContext.getUserId();
if (file.isEmpty()) {
throw new BusinessException("文件不能为空");
}
// 验证文件类型
String contentType = file.getContentType();
if (allowedTypes != null && allowedTypes.length > 0) {
boolean validType = false;
for (String allowedType : allowedTypes) {
if (contentType != null && contentType.startsWith(allowedType)) {
validType = true;
break;
}
}
if (!validType) {
throw new BusinessException("不支持的文件类型: " + contentType);
}
}
// 验证文件大小
if (file.getSize() > maxFileSize * 1024 * 1024) {
throw new BusinessException("文件大小超出限制: " + maxFileSize + " MB");
}
try {
// 计算文件MD5可选用于文件完整性校验
String md5 = DigestUtil.md5Hex(file.getInputStream());
log.info("文件MD5: {}", md5);
// 调用MinioUtil上传文件使用默认桶名按userId划分文件夹
String filePath = minioUtil.uploadImage(file, String.valueOf(userId));
log.info("文件上传成功: {}, 文件路径: {}", file.getOriginalFilename(), filePath);
return Response.success(minioUtil.processMinioResource(filePath, CommonConstants.MINIO_PATH_TIMEOUT));
} catch (IOException e) {
log.error("文件上传失败: {}", e.getMessage(), e);
throw new BusinessException("文件上传失败");
}
}
}