如何将其他数据添加到AJAX文件上传中

时间:2019-12-02 15:44:08

标签: jquery ajax flask

我正在使用AJAX将图像文件上传到Flask端点。我想在同一AJAX上传文件中将元数据(作者,出版日期等)与文件一起发送。

我的JQuery代码如下:

    $("#upload_btn").click(function() { 
        var fd = new FormData(); 
        var file = $('#file_input')[0].files[0]; 
        // Build AJAX request
        fd.append('file', file);               // This works fine, the file is uploaded
        fd.append('author', 'Test Auth');      // I'd expect this to upload but it doesn't
        fd.append('pub_date', '01 Jan 2018');  // nor this
        $.ajax({ 
            url: '{{ upload_url }}', 
            type: 'post', 
            data: fd, 
            contentType: false, 
            processData: false, 
            xhr: function () {
                var xhr = new window.XMLHttpRequest();
                xhr.upload.addEventListener("progress", function (evt) {
                    if (evt.lengthComputable) {
                        var percentComplete = evt.loaded / evt.total;
                        percentComplete = parseInt(percentComplete * 100);
                        $('#progress').text(percentComplete + '%');
                        $('#progress').css('width', percentComplete + '%');
                    }
                }, false);
                xhr.addEventListener("load", function(evt){ 
                    var results = JSON.parse(xhr.responseText);
                    if(results.result == 'ok'){ 
                        $('#progress_status').text('SUCCESS: Upload complete');
                    } 
                    else{ 
                        $('#progress_status').text('APP ERROR: ' + results.message);
                    } 
                }, false);
                xhr.addEventListener("error", function(jqXHR, textStatus, exception){ 
                    $('#progress_status').text('SYSTEM ERROR');
                }, false);
                return xhr;
            },
        }); 
    }); 

在Flask端点上,我希望能够使用:

    print(request.data['author']) 

或可能:

    print(request.data.author)

但没有用。

我的Flask端点代码如下:

@targets.route("/upload_file", methods=["POST"])
def upload_file():
    print("AA: Entered upload_file function")
    print(request.data['author'])
    file = request.files["file"]
    filename = secure_filename(file.filename)
    file_handle = save_user_file(file)
    if file_handle is None:
        results = {"result": "error",
                   "message": "Could not save file",
                   "file_handle": None}
    else:
        results = {"result": "ok",
                   "message": "File uploaded",
                   "file_handle": file_handle}
    return jsonify(results)

print(request.data ['author'])语句引发错误:

TypeError: byte indices must be integers or slices, not str

很显然,数据是一个Blob,并且我没有访问请求对象的正确元素。

我应该使用哪种方法与上载的文件一起发送元数据并在端点处检索它?

1 个答案:

答案 0 :(得分:1)

表单数据以request.form的形式附加到请求中,request.data始终是字符串AFAIK。因此,只需尝试author = request.form["author"]或类似的方法。