S3 pre-signed url is opening the file in browser instead of downloading it

Viewed 25

I'm uploading a txt file to an S3 folder and generating a pre-signed URL to be accessed later.

Code to upload the file:

try{
            context.getLogger().log("Uploading a new object to S3 from a file\n");
            PutObjectRequest request;
            String keyObject = folder + "/" + fileName;
            request = new PutObjectRequest(bucket, keyObject, file.getAbsoluteFile());
            s3Config.getS3Client().putObject(request);
            return "SUCCESS:" + s3Config.getS3Client().getUrl(bucket, folder + "/" + fileName);
        }

Code to generate URL:

try {
            java.util.Date expiration = new java.util.Date();
            long expTimeMillis = Instant.now().toEpochMilli();
            expTimeMillis += 1000 * 60 * 60;
            expiration.setTime(expTimeMillis);

            System.out.println("Generating pre-signed URL.");
            GeneratePresignedUrlRequest generatePresignedUrlRequest =
                    new GeneratePresignedUrlRequest(bucketName, objectKey)
                            .withMethod(HttpMethod.GET)
                            .withExpiration(expiration);
            URL url = s3Config.getS3Client().generatePresignedUrl(generatePresignedUrlRequest);
            return url;

        }

here, in objectKey, I'm just passing folder+"/"+filename(filename contains the extension .txt as well).

Everything is working as expected but earlier when I clicked on the presigned URL, it used to download the file but now it is just opening the file in the browser.

Nothing in browser settings was changed. Is there anything that can be configured in S3? Or should I add some sort of Content-Disposition to the putObject request in order to force download the file. Is yes, how can I set the content disposition correctly considering I have .txt file

EDIT, It worked when I pass Content-disposition in the metadata of the PutObjectRequest while uploading the file to S3. When the url is generated for this file, it automatically downloads instead of opening in browser.

Code:

PutObjectRequest request;
            String keyObject = folder + "/" + fileName;
            request = new PutObjectRequest(bucket, keyObject, file.getAbsoluteFile());
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentDisposition("attachment");
            request.setMetadata(metadata);
            s3Config.getS3Client().putObject(request);
0 Answers
Related