How do I load an image from HTML to Flask?

Issue

I have an HTML page that lets you upload a picture and displays it (very simple). But how do I send that particular loaded image into my flask app so that I could, say, perform some image processing on it using python’s openCV or PIL packages?

Solution

Disclaimer

I’ve done similar thing recently, It may not be a 100% solution for you, but using parts of this code will propably solve all of your problems.

Flask Code

This part gets all files uploaded from browser and saves them with their respected extensions.

if request.method=="PUT":
        for f in request.files.getlist("Files"): #<---- note 1
            f.save(os.path.join(Path_To_Folder, f.filename)) 
        return jsonify({"result": "res"}), 200 #status code is only thing important here

HTML

This just allows you to select file(s) from your device

<input type="file" id="file_loader" multiple/>

JavaScript

This code

const file_loader = document.getElementById("file_loader");

file_loader.onchange = async function(e){   
    alert("Upload started")
    let sending = new FormData(); //creates form data object

//this for loop adds all files you selected to a form object
    for (let i = 0; i < file_loader.files.length; i++) {        
        sending.append("Files", file_loader.files[i]);   //<---- note 1 
    }

//this part just sends all the files to server
    const podaci = await fetch(url_filesistem, {
        method: "PUT",
        body: sending,        
    })
    .then((response) => response.json())
    .then((pod) => {return pod;}); 
       
//removing all selected files from an input, so every time you want to select files
//its just those files, not ones previously selected
    while (file_loader.length > 0) {
        file_loader.pop();
    } 
    alert("Finnished uploading")    
}

Note 1

String "Files" mentioned in both lines needs to be the same in order for this method to work.

Advice

First save all the files on the server and then do the processing. I don’t know what "f" object from for loop in python contains, therefore I don’t know whether you can process them immediately.

Feel free to ask me anything regarding my code!

Best regards!

Answered By – Андреја Јанковић

Answer Checked By – Timothy Miller (AngularFixing Admin)

Leave a Reply

Your email address will not be published.