Tyali Nexi
Tyali Nexi

Reputation: 15

Upload file to folder under AS S3 using Java

I am trying to upload files to a folder under a bucket in s3, but I have a problem with the path. Here's an example of code :

import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
import software.amazon.awssdk.services.s3.model.S3Exception;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.core.sync.ResponseTransformer;

public class S3Uploader {

    public static void main(String[] args) {
        String bucketName = "user-bucket";
        String folderName = "user-data";
        String fileName = "user.txt";
        String fileContent = "test data";

        Region region = Region.US_EAST_1;

        S3Client s3 = S3Client.builder().region(region).build();

        try {
            PutObjectRequest request = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(folderName + "/" + fileName)
                    .build();

            s3.putObject(request, RequestBody.fromString(fileContent));
            System.out.println("File uploaded successfully to S3!");
        } catch (S3Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}

The code shows an error and transforms or encodes "/" to "%2f", how to solve this error ?

Error uploading object: exception while calling s3.PutObject: [Errno 2] No such file or directory: '/persisted-data/s3/assets/user-bucket/user-data%2fuser.txt@null'

Why it show @null ?

I use localstack with dokcer-compose command!

Upvotes: 0

Views: 103

Answers (1)

smac2020
smac2020

Reputation: 10734

This AWS SDK for Java V2 code works. The only difference that i see is RequestBody.fromFile(new File(objectPath).

public class S3Uploader {

    public static void main(String[] args) {
        String bucketName = "myjunebucketxxx";
        String objectPath = "C:\\AWS\\AdobePDF.pdf";
        String objectKey = "books/Adobe.pdf";
        Region region = Region.US_EAST_1;
        S3Client s3 = S3Client.builder().region(region).build();
        putS3Object(s3, bucketName, objectKey, objectPath);

    }

    public static void putS3Object(S3Client s3, String bucketName, String objectKey, String objectPath) {
        try {
            PutObjectRequest putOb = PutObjectRequest.builder()
                .bucket(bucketName)
                .key(objectKey)
                .build();

            s3.putObject(putOb, RequestBody.fromFile(new File(objectPath)));
            System.out.println("Successfully placed " + objectKey + " into bucket " + bucketName);

        } catch (S3Exception e) {
            System.err.println(e.getMessage());
            System.exit(1);
        }
    }
}

Note that my PDF doc is in the correct location:

enter image description here

Upvotes: 1

Related Questions