【问题标题】:Python flask upload file using ajax request.files emptyPython烧瓶使用ajax request.files上传文件为空
【发布时间】:2018-12-30 05:04:51
【问题描述】:

我正在尝试将大约 1.62MB 的图像上传到使用烧瓶编写的端点。 request.files 对象始终为空。我检查了以下问题,但没有运气:

这是我的服务器:

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()

我的客户:

<!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>

对我来说,一切看起来都很干净,我不知道我哪里出错了。请求对象中的 files 属性始终为空。我还尝试与邮递员一起使用带有表单数据键=文件和值=上传文件和标题内容类型=“多部分/表单数据”的发布请求。非常感谢任何帮助!

【问题讨论】:

    标签: python flask file-upload


    【解决方案1】:

    我做了一些更改并使其工作:

    首先,在 javascript 部分更改您从哪个 html 元素中读取数据:

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

    其次,我尝试按如下方式获取上传的图片:(@cross_origin() 仅在您尝试上传到本地主机时才需要)

    @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")
    

    【讨论】:

    • 坦率地说,在尝试解决这个问题时,我尝试了没有跨源装饰器的这些更改,但它对我不起作用。不过,我将复制粘贴您的代码并尝试一下。我通过使用表单的提交来完成它,但我想使用 AJAX 而不是表单提交。非常感谢
    猜你喜欢
    • 2020-06-07
    • 1970-01-01
    • 2020-11-15
    • 2018-10-11
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 2019-03-23
    • 2021-06-02
    相关资源
    最近更新 更多