Reputation: 829
I'm using minio
java client for storing files in minio that are uploaded by users.
I want to store each file with a UUID as objectName and also store the original fileName as user-metadata. When generating the download url for that file, I want to instruct minio to change the downloading fileName to the original fileName. This ensures that when users download the file, they receive it with the same name they used when uploading it.
import org.springframework.web.multipart.MultipartFile;
public String uploadInMinio(MultipartFile file, String bucketName) {
String objectName = UUID.randomUUID().toString();
Map<String, String> userMetaData = new HashMap<>();
if (file.getOriginalFilename() != null)
userMetaData.put("file-name", file.getOriginalFilename());
minioClient.putObject(PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.contentType(file.getContentType())
.userMetadata(userMetaData)
.stream(file.getInputStream(), file.getInputStream().available(), -1)
.build());
StatObjectResponse statObj = minioClient.statObject(StatObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build());
String fileName = statObj.userMetadata().get("file-name");
String contentDisposition = URLEncoder.encode("attachment; filename=\"%s\"".formatted(fileName), StandardCharsets.UTF_8);
return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
.bucket(bucketName)
.object(objectName)
.extraQueryParams(Map.of("response-content-disposition", contentDisposition))
.expiry(1, TimeUnit.HOURS)
.method(Method.GET)
.build());
}
As you see, I've used response-content-disposition
query param in invoking getPresignedObjectUrl
.
When using the generated url in browser, the file with objectName.fileExtension
will be downloaded not fileName.fileExtension
.
For example for the file with sample.png
name, the generated url is:
http://127.0.0.1:9000/test/a58c95f9-b4c2-4a80-8040-e2af191ccf84?response-content-disposition=attachment%253B%2Bfilename%253D%2522sample.png%2522&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=minioadmin%2F20240201%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20240201T152135Z&X-Amz-Expires=10000&X-Amz-SignedHeaders=host&X-Amz-Signature=dca0ad196ca74c395198702952c7a038f54321cad212e85be92ca1600b7e6e17
By entering the url in browser, the downloading file name is a58c95f9-b4c2-4a80-8040-e2af191ccf84.png
instead of sample.png
. Is there any solution or other way to do this?
Upvotes: 2
Views: 2178
Reputation: 1
String contentDisposition = URLEncoder.encode("attachment; filename=\"%s\"".formatted(fileName), StandardCharsets.UTF_8);
no need URLEncoder.encode hha
like this : String contentDisposition = "attachment;filename=\"%s\"".formatted(fileName);
Upvotes: 0
Reputation: 1
The Problem in your Code is this String objectName = UUID.randomUUID().toString();
You can to solve this problem by use String objectName = file.getOriginalFilename();
i hope this was helpfully for you :-)
Upvotes: 0