1

I'm trying to upload file to AWS S3 bucket using Lambda server less application written in Java.

I'm hitting the endpoint with file using postman option binary (screenshot attached).

enter image description here

And I'm receiving binary content as string in my endpoint like as follows (screenshot attached).

enter image description here

I'm trying to convert this binary string to byte array and upload to S3 bucket.

I'm getting success response, But when i downloads the file / image it's looks like not an actual file.

Sample code:

@Override
public ServerlessOutput handleRequest(ServerlessInput serverlessInput, Context context) {
    ServerlessOutput output = new ServerlessOutput();
    String keyName = UUID.randomUUID().toString();
    String content = serverlessInput.getBody();
    byte[] encoded = this.toBinary(content).getBytes();
    ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(encoded.length);
    metadata.setContentType(PNG_MIME);
    s3.putObject(new PutObjectRequest(
        ARTICLE_BUCKET_NAME,
        keyName,
        new ByteArrayInputStream(encoded),
        metadata)
    );
    output.setBody("Successfully inserted article ");
}

private String toBinary(String data) {
    byte[] bytes = data.getBytes();
    StringBuilder binary = new StringBuilder();
    for (byte b : bytes) {
        int val = b;
        for (int i = 0; i < 8; i++) {
            binary.append((val & 128) == 0 ? 0 : 1);
            val <<= 1;
        }
        binary.append(' ');
    }
    return binary.toString();
}
Richardson. M
  • 852
  • 2
  • 17
  • 28
  • Ae you uploading an image? –  Apr 25 '20 at 19:41
  • Yes, I'm uploading image – Richardson. M Apr 25 '20 at 19:42
  • Hmm, i'm not sure, but don't you need to read the binary contents from post ( i assume, that's a post request) as form [multipart](https://stackoverflow.com/a/19712083/8725011)? Otherwise the binary data will be interpreted as UTF-8, and results in gargabe. –  Apr 25 '20 at 19:43
  • It looks like you are using `getmarkus/spring-integration-lambda-proxy`. I don't see any support for multipart documents in their docs. The body they expose is a string, which will work for simple things like JSON content. File uploads, however, are contained in sections in a multipart document in the body of the request, not as a simple string taking up the entire body. You might want to ask them how to parse the file content. Also, consider modifying your solution so that your Lambda function doesn't even see the file upload, but it goes straight to S3 from the client via pre-signed URL. – jarmod Apr 26 '20 at 00:12
  • Hi, Thank you for your support. – Richardson. M Apr 26 '20 at 18:01
  • you can zip it! – kirilv May 03 '22 at 14:47

0 Answers0