3

My flask python app return an image as a response from a POST request:

def upload_file():
    if request.method == 'POST':
        return send_file('1.png', mimetype='image/png')

Then I want to use javascript and jquery ajax to do the request, and the response is:

success: function(img_response) {
            console.log(img_response);
}

�PNG ��� IHDR����������?1�� �IDATx����nIv��vdU�Ѓ�ۀm6f`�����?���W3�1��%6Y��ER�xh�Pb��]�R�DfeFF�qo��_����O�4�]J$��.�%E�%E�ɲ$)...

How can I render this type of file in browser? Maybe is better decode the image in base64 in flask, but how can I do it?

2
  • The file is not sent to the browser as a binary file. The HTTP protocols requires this file be character encoded. That happens behind the scenes. In order to use the file on the client you create and new Image() object with that file from the server and place it into the DOM. Don't worry about binary/encoding/decoding etc. Commented Feb 27, 2018 at 22:44
  • Thank you. So how can I do it? I am using this with no success: success: function(img_response) { $('#image').html('<img src="data:image/png;base64,' + img_response + '" />'); }, Commented Feb 27, 2018 at 22:49

1 Answer 1

1

You should take a look here for encoding a binary to base64 with python. Once you got it, send the string to your app (frontend) as a response, then you can add something like:

<img id="myImgTag" src="data:image/png;base64, YOUR_BASE64_STRING_FROM_RESPONSE"></img>

You can add it with javascript with something like:

let img = document.getElementById('myImgTag').setAttribute('src','data:image/png;base64, YOUR_BASE64_STRING_FROM_RESPONSE')

====EDIT===

To read the file and encode it to base64 do the following:

import base64
...
myImage = open('your_file_name','rb')
myBase64File = base64.b64encode(myImage.read())

Then just use Flask to send 'myBase64File' var as you want (might be inside a JSON, as plain text, etc.)

Sign up to request clarification or add additional context in comments.

2 Comments

Flask require only the filename... so how can I encode to base64 before send the file? I tryed this but it does't work: return send_file( base64.b64encode('1.png'), mimetype='image/png')
added more information to my post. You need to send the base64 string as a string, not as a file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.