Home > Back-end >  Form image data, how to handle image?
Form image data, how to handle image?

Time:02-23

So I send a Form to my Flask App and wish to receive the Form image data input and pass it to another function.

Example of form:

    <form action="https://example.com/api/accept_form" method="POST" enctype="multipart/form-data">
    <label for="fileupload"><input type="file" name="fileupload" value="fileupload" id="fileupload"  accept="image/*">
     Select a file to upload</label>
    <br><button id="submit">Post to Instagram</button>
    </form>

On the flask app:

def image_function(image):
     #DO SOMETHING WITH THE IMAGE

@main.route("/api/accept_form", methods=["POST"])
def manipulate_image():
    image = request.form["fileupload"]
    image_function(image)

I can see how the image data looks using the print command:

request.files["fileupload"] = <FileStorage: '666650673.jpg' ('image/jpeg')>
request.files["fileupload"].read() = b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00H\x00H\x00\x00\xff\xe1\x00 and so on ...'

How do I pass the image to another function in the Flask App as if it was the original .jpg submitted, called from the Flask Apps current directory using "./666650673.jpg"?

References:

https://linuxhint.com/python-string-decode-method/

https://stackoverflow.com/a/2324133/14843373

https://github.com/williballenthin/python-evtx/issues/43

CodePudding user response:

My mistake, as @teddybearsuicide pointed out was that I was passing a file handle and not a file pointer.

Maybe there is a better way but I just saved it locally on the EC2 based on this

Solution

request.files["image"].save("./imageToSave.jpg")

And called it as you would any file in your directory.

image = "./imageToSave.jpg"

I would prefer not to have had to save it so if anyone knows how to pass the file handle directly to achieve the same effect that would be great.

  • Related