使用 XMLHtttpRequest 将照片上传到 Flask 网络服务器 [英] Uploading a photo using XMLHtttpRequest to a Flask webserver

查看:54
本文介绍了使用 XMLHtttpRequest 将照片上传到 Flask 网络服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 WinJS 应用程序并使用 XMLHttpRequest 将照片作为 blob 发送到 Flask 网络服务器.

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);
        });
    });

这会产生以下 HTTP 请求:

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

在 Flask 网络服务器上处理请求

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

我收到以下错误:

TypeError: 'ImmutableMultiDict' object is not callable

我有几个问题找不到答案:

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

  • 我是否以正确的格式发送数据?我是否正确地将数据附加到我的表单中?
  • 我的 HTTP 内容类型是否正确?
  • 我是否试图错误地从 HTTP 请求中提取文件?

谢谢!

推荐答案

尝试替换这个:

f = request.files('file')

与:

f = request.files['file']

这篇关于使用 XMLHtttpRequest 将照片上传到 Flask 网络服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆