0

I am trying to upload an image about 1.62MB to an end point written using flask. the request.files object is always empty. I've checked the following questions but no luck:

here is my server:

from flask import Flask, request, jsonify, render_template
import sys

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = r"C:\Temp"
app.debug = True

@app.route("/demo-upload", methods=["GET", "POST"])
def ProcessImage():
    if request.method == "POST":
        print(request.files)
        try:
            if 'file' in request.files:
                with open("test-upload.png", "wb") as iFile:
                    print(request['file'])
                    iFile.write(request.files['file'])
        except Exception as e:
            print(e)
        return jsonify("Ok")

@app.route("/", methods=["GET"])
def DemoIndexPage():
    return render_template("index.html")

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

my client:

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"
            integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
            crossorigin="anonymous"></script>
    <title>Demo</title>
</head>
<body>
    <h1 style="text-align: center">Status Demo</h1>
    <span>upload image to process.</span><br/>
        <form id="FileForm" name="file" enctype="multipart/form-data">
            <input type="file" name="file" id="File" />
            <input type="button" name="submit" value="submit" onclick="ProcessImage()" />
        </form>
    <p id="status" hidden>Success!</p>
    <script>
        function ProcessImage()
        {
            var form_data = new FormData($('#File')[0]);
            console.log(form_data)
            $.ajax({
                type: 'POST',
                url: '/demo-upload',
                data: form_data,
                contentType: false,
                cache: false,
                processData: false,
                async: false,
                success: function (data) {
                    console.log('Success!');
                    $("#status").show();
                },
            });
        }
    </script>
</body>
</html>

everything looks clean to me and I do not know where I am going wrong. the files attribute in the request object is always empty. I also tried with postman using post request with form-data key = file and value = uploaded a file, and a header content-type = "multipart/form-data". any help is appreciated thanks a lot!

1 Answer 1

3

I made a few changes and make it work:

First, change which html element you read the data from in javascript part:

var formDataRaw = $('#FileForm')[0];
var form_data = new FormData(formDataRaw);

Second, I tried to obtain the uploaded image as follows: (@cross_origin() is only required if you try to upload to your localhost)

@app.route("/demo-upload", methods=["GET", "POST"])
@cross_origin()
def ProcessImage():
    if request.method == "POST":
        print(request.files)
        try:
            if 'file' in request.files:
                imageFile = request.files['file']
                savePath = "/somewhere/somewhere/something.png"
                imageFile.save(savePath)
        except Exception as e:
            print(e)
        return jsonify("Ok")
Sign up to request clarification or add additional context in comments.

1 Comment

frankly, while trying to solve this I tried these changes without the cross origin decorator and it did not work for me. I am going to copy paste your code though and give it a try. I got it working through using form's submit but I wanted to use AJAX instead of form submit. thanks a lot

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.