Limit upload size to S3 with presigned URL

4.2k Views Asked by At

Using the below code I can sign an upload URL to Amazon S3. What I would like to add to this is the ability to limit the upload size.

AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider(configFileName, profileName)); 
GeneratePresignedUrlRequest generateUploadPresignedUrlRequest = new GeneratePresignedUrlRequest(BUCKETNAME, key); 
generateUploadPresignedUrlRequest.setMethod(HttpMethod.PUT);  
generateUploadPresignedUrlRequest.setExpiration(getFutureDate( 2*DAYS )); 
URL uploadURL = s3client.generatePresignedUrl(generateUploadPresignedUrlRequest);

I am aware that what I need is to add a policy that sets the "content-length-range". Example: ["content-length-range", 0, 10485760]

But all my attempts to encode this in Java have failed with 403 Forbidden.

EDIT: I ommitted non-working code and adding this before the generatePresignedUrl which was my "fix".

Date futureDate = getFutureDate( 2*DAYS ); 
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); 
String date = df.format(futureDate);
String policy = "{ \"expiration\": \""+date+"\","+
                            "\"conditions\": [" +
                                "{\"bucket\": \""+BUCKETNAME+"\" }," +
                                "['content-length-range', 0, 25000]," +
                            "]" +
                    "}"; 
generateUploadPresignedUrlRequest.addRequestParameter("Policy", policy);
2

There are 2 best solutions below

1
On

LOL - 5 min after posting I found my error...

ANSWER - note the "Policy" instead of "policy" (capital P) generateUploadPresignedUrlRequest.addRequestParameter("Policy", policyStr);

0
On

I tried this code, aws s3 fails and returns:

<?xml version="1.0" encoding="UTF-8"?> <Error><Code>MalformedPolicy</Code><Message>Policies must be valid JSON and the first byte must be '{'</Message><RequestId>D6617E1A36C438A4</RequestId><HostId>nsBW8QdBaRWXVWRv+FYQc9mWPab2ZQ4N85I5CWh7He2IxaX+OkZL+u01ZA2Cgihb0Oaa1o1/7A0=</HostId></Error>

I've tried encode policy to Base64(as it says here), it gives same result.

It seems, that policy field does not work with presigned urls.