diff --git a/backend/src/main/java/com/designhub/service/S3Service.java b/backend/src/main/java/com/designhub/service/S3Service.java index 2483fe9..4dccc6b 100644 --- a/backend/src/main/java/com/designhub/service/S3Service.java +++ b/backend/src/main/java/com/designhub/service/S3Service.java @@ -89,11 +89,20 @@ public class S3Service { // 创建S3客户端 S3Client s3Client = createS3Client(config); + // 对原始文件名进行URL编码,用于Content-Disposition头 + String encodedFilename; + try { + encodedFilename = java.net.URLEncoder.encode(originalFilename, "UTF-8").replace("+", "%20"); + } catch (Exception e) { + encodedFilename = originalFilename; + } + String contentDisposition = "attachment; filename*=UTF-8''" + encodedFilename; + // 根据文件大小选择上传方式 if (file.getSize() > MULTIPART_THRESHOLD) { // 大文件使用分块上传 log.info("文件大小 {} bytes,使用分块上传: {}", file.getSize(), originalFilename); - uploadMultipart(s3Client, config, file, filePath); + uploadMultipart(s3Client, config, file, filePath, contentDisposition); } else { // 小文件使用普通上传 log.info("文件大小 {} bytes,使用普通上传: {}", file.getSize(), originalFilename); @@ -101,6 +110,7 @@ public class S3Service { .bucket(config.getBucket()) .key(filePath) .contentType(file.getContentType()) + .contentDisposition(contentDisposition) .build(); s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(file.getInputStream(), file.getSize())); } @@ -134,7 +144,7 @@ public class S3Service { /** * 分块上传大文件 */ - private void uploadMultipart(S3Client s3Client, S3Config config, MultipartFile file, String filePath) throws IOException { + private void uploadMultipart(S3Client s3Client, S3Config config, MultipartFile file, String filePath, String contentDisposition) throws IOException { String uploadId = null; try { @@ -143,6 +153,7 @@ public class S3Service { .bucket(config.getBucket()) .key(filePath) .contentType(file.getContentType()) + .contentDisposition(contentDisposition) .build(); CreateMultipartUploadResponse createResponse = s3Client.createMultipartUpload(createRequest);