fix: 修复文件下载时文件名乱码问题
- 上传时设置 Content-Disposition 头保存原始文件名 - 支持中文文件名的 URL 编码
This commit is contained in:
parent
3b47701e81
commit
3b6f5f9659
@ -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);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user