Uploading a photo using XMLHtttpRequest to a Flask webserver

☆樱花仙子☆ 提交于 2021-02-08 04:40:28

问题


I'm creating a WinJS app and using XMLHttpRequest to send a photo as a blob to a Flask webserver.

openPicker.pickSingleFileAsync().then(function (file) {
        file.openAsync(Windows.Storage.FileAccessMode.read).done(function (stream) {
            var blob = MSApp.createBlobFromRandomAccessStream("application/octet-stream", stream);
            var fdata = new FormData();
            fdata.append("file", blob, "photo.jpg");

            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open("POST", "http://127.0.0.1:5000/api/addPhoto", true);
            xmlhttp.setRequestHeader("Content-type", "multipart/form-data");
            xmlhttp.send(fdata);
        });
    });

This results in the following HTTP request:

POST http://127.0.0.1:5000/api/addPhoto HTTP/1.1
Accept: */*
Content-Type: application/octet-stream, multipart/form-data; boundary=---------------------------7dd2a320aa0ec0
Accept-Language: en-US,en;q=0.7,ja;q=0.3
UA-CPU: AMD64
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0; MSAppHost/1.0)
Host: 127.0.0.1:5000
Content-Length: 9471100
Connection: Keep-Alive
Pragma: no-cache

-----------------------------7dd2a320aa0ec0
Content-Disposition: form-data; name="file"; filename="photo.jpg"
Content-Type: application/octet-stream

Handling the request on the Flask web server

UPLOAD_FOLDER = '/images'
@app.route('/api/addPhoto', methods=['POST'])
def addPhoto():
        if request.method == 'POST':
            f = request.files['file']
            if f and allowed_file(f.filename):
                    return "error" #add error response here
        else:
                    filename = secure_filename(f.filename)
                    f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
                    f.close
                    return "ok" #add success response here

I'm getting the following error:

TypeError: 'ImmutableMultiDict' object is not callable

I have a few questions that I can't find answers for:

  • Am I sending the data in the right format? Am I appending data to my form correctly?
  • Are my HTTP content types correct?
  • Am I trying to pull the file from the HTTP request incorrectly?

Thank you!


回答1:


try to replace this:

f = request.files('file')

with:

f = request.files['file']


来源:https://stackoverflow.com/questions/16003266/uploading-a-photo-using-xmlhtttprequest-to-a-flask-webserver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!