0

I'm trying to upload an image to an Bucket on AWS with POST, how should I decode in python3?

When I use a program to make a method Post (Insomnia), it saves correctly in Bucket. But when I do it with Ajax it also saves with the same file size, but when I open the image it doesn't work, the image is corrupted.

Send with AJAX:

var form;
$("#file").change(function() {
    form = new FormData();
    form.append('file', event.target.files[0]);
});


function uploadFile(){
    $.ajax({
        url: 'myUrlApi',
        crossDomain : true,
        processData: false,
        data: form,
        contentType: 'image/png',
        type: 'POST',
        success: function (data) {
            console.log(data)
        }
    });
}

Retrieve in python3 Lambda to save in Bucket:

import boto3
import base64


def lambda_handler(event, context):

    s3 = boto3.client("s3")
    get_file_content = event["content"]
    decode_content = base64.b64decode(get_file_content)
    s3.put_object(Bucket="mybucket", Key="exampleUpload.png", Body=decode_content)

I am not able to reproduce the same type of file when it is sent by Insomnia, so it is corrupting the image.

What type of file do I get when I send a file in FormData with AJAX?

I also tried to send the image in a string on Base64, but it also corrupted.

1 Answers1

0

I managed to solve my problem.

I converted my image to Base64, and sent it to Lambda to save in AWS Bucket. Lambda receives the Data converted to Base64 again, so I decoded it twice and got the right image.

var fileInB64 = ''

function getBase64(file) {
    var reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function () {
        fileInB64 = reader.result.split(',')[1];
    };
    reader.onerror = function (error) {
        console.log('Error: ', error);
    };
}

$("#file").change(function() {
    var file = document.querySelector('.divFile > input[type="file"]').files[0];
    getBase64(file)
});

function uploadFile(){
    $.ajax({
        url: 'myUrlApi',
        crossDomain : true,
        processData: false,
        data: fileInB64,
        contentType: 'image/png',
        type: 'POST',
        success: function (data) {
            console.log(data)
        }
    });
}

And in Lambda python3 i decoded it twice and got the right image.

import boto3
import base64


def lambda_handler(event, context):

    s3 = boto3.client("s3")
    get_file_content = event["content"]

    stringBase64 = base64.b64decode(get_file_content)
    toBase64FromBase64 = base64.b64decode(stringBase64)

    s3.put_object(Bucket="mybucket", Key="exampleUpload.png", Body=toBase64FromBase64)