Retrieve image name in python from form

Question:

on the contnue of the my prevous question : find answer

i have fixed hmtl code and it is here :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Select image</title>
</head>
<body>
    <form action="{{ url_for('image_shape')}}"method="post">
        <label for="img">Select image</label>
        <input type="file" id="img" name="img" accept="image/*" onchange="displayImage(this)">
        <br>
        <img id="selectedImg" src="#" alt="Selected Image" style="display:none; max-width: 300px;">
        <br>
        <input type="submit">
    </form>

    <script>
        function displayImage(input) {
            var file = input.files[0];
            var reader = new FileReader();
            reader.onload = function(e) {
                var imgElement = document.getElementById('selectedImg');
                imgElement.src = e.target.result;
                imgElement.style.display = 'block';
            };

            reader.readAsDataURL(file);
        }
    </script>
<h4 style="color:Violet;">
                   {{ prediction_text }} </h4>
</body>
</html>

but what i want now is the following : when the user upload image, i want to extract name of this image and read in python using opencv, for this i have wrote following code(right now no opencv yet)

from flask import Flask, request,render_template
from bs4 import BeautifulSoup
import re

app =Flask(__name__)
@app.route('/')
def image_shape():
    code =[x for x in request.form.values()]
    text= f'i have {code}'

    return render_template("Select_IMage.html",prediction_text=text)


if __name__=="__main__":
    app.run(debug=True)

when i am running, i am getting following part :
enter image description here

idea is that selecting of image works fine, but this line :

 code =[x for x in request.form.values()]

does not return anything,i have tried before several experiment iwth form values, maybe here selecting of image does not correspond to form and how can i return name of the image that is displayed next to select button? thanks in advance

Asked By: AI ML

||

Answers:

To upload the image, a form of type multipart/form-data is required, which you can specify using the enctype attribute.

<form enctype="multipart/form-data">
    <!-- ... -->
</form>

Uploaded files can be requested under Flask from the dict request.files. You will receive an object of type FileStorage, from which you can get the filename and which you can save in a suitable location and then open it with opencv.

You can find detailed instructions for uploading files here.


First of all, when you send a form of type POST, you should accept this request type within the route. Within your endpoint you can then use request.method to distinguish whether it is a POST or GET request.

Form data can be requested using the name attribute of the input field. Unlike the values of normal form fields, files, as described, are not stored in request.form but in request.files.
The received FileStorage object has, among other attributes, one that contains the file name.

from flask import (
    Flask, 
    render_template, 
    request
)

app = Flask(__name__)

@app.route('/', methods=['GET','POST'])
def image_shape():
    text = 'Please select and upload a file.'
    if request.method == 'POST':
        file = request.files.get('img')
        if file and file.filename != '': 
            text=f'I have {file.filename}'
    return render_template('Select_IMage.html', prediction_text=text)

if __name__=="__main__":
    app.run(debug=True)
Answered By: Detlef
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.