1

I am changing my form submission to make it more fluid via using fetch.

In order to process the value of my input image:

<input name="perfil" type='file' id="imageUpload />

And then, in order to upload it to Amazon S3,

I do this in my views.py:

if request.method == "POST" image = request.FILES['perfil'] im = Image.open(image) output = BytesIO() rgb_im = im.convert('RGB') rgb_im.save(output, format='JPEG', quality=90) output.seek(0) s3.Bucket('bucketname').upload_fileobj(output, request.user.email + '.profileImage') 

But now (because i'm trying to implement fetch), I am getting the image file like this:

fetch(`url`, { method: 'POST', body: JSON.stringify({ image: document.querySelector('#imageUpload').files[0], }), headers: { "Content-type": "application/json; charset=UTF-8", "X-CSRFToken": getCookie('csrftoken') } }) } 

The problem is that when I do request.body['image`] in the server (views.py), all I'm getting is this: "image":{}

And I don't know how to process this file in JS before I send it to the server (that will end up uploading it to amazon s3)

1 Answer 1

1

With this Example you can upload Images on a Server!

// Select your input type file and store it in a variable const input = document.getElementById('fileinput'); // This will upload the file after having read it const upload = (file) => { fetch('http://www.example.net', { // Your POST endpoint method: 'POST', headers: { // Content-Type may need to be completely **omitted** // or you may need something "Content-Type": "You will perhaps need to define a content-type here" }, body: file // This is your file object }).then( response => response.json() // if the response is a JSON object ).then( success => console.log(success) // Handle the success response object ).catch( error => console.log(error) // Handle the error response object ); }; // Event handler executed when a file is selected const onSelectFile = () => upload(input.files[0]); // Add a listener on your input // It will be triggered when a file will be selected input.addEventListener('change', onSelectFile, false); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.