为什么ajax将FormData放入request.data而不是request.files?

时间:2017-06-29 13:13:28

标签: ajax flask upload

Flask,我想通过HTML中的AJAX调用上传图像文件。

我写了这个Javascript:

function mysubmit(input){
    var file_input = document.getElementById('file-input-left');
    var form_data = new FormData();
    var file = file_input.files[0];
    alert(file);
    form_data.append('file', file);
    $.ajax({
        type: 'POST',
        url: '/calc_full_result',
        data: form_data,
        contentType: false,
        cache: false,
        processData: false,
        async: false,
        success: function(data){
            alert('Success!');
        },
    });
}

HTML:

<div class="image-holder">
    <form action="/calc_full_result" id="upload-form-left" name="form-left" method=post enctype=multipart/form-data>
    <div class="image-holder-left">
        <div class="image-upload">
        {% if img_left %}
        <label id="upload-left-label" for="file-input-left"><img id="left-image" src="data:image/png;base64, {{img_left}}"/></label>
        {% else %}
        <label id="upload-left-label" for="file-input-left"><img id="left-image" src="{{url_for('static', filename='upload_fill.png')}}" /></label>
        {% endif %}
        <input id="file-input-left" type=file name=file onchange="mysubmit(this)"/>
        </div>
    </div>
    <form action="/calc_full_result" id="upload-form-right" name="form-right" method=post enctype=multipart/form-data>
    <div class="image-holder-right">
        <div class="image-upload">
        {% if img_right %}
        <label id="upload-right-label" for="file-input-right"><img id="right-image" src="data:image/png;base64, {{img_right}}"/></label>
        {% else %}
        <label id="upload-right-label" for="file-input-right"><img id="right-image" src="{{url_for('static', filename='upload_fill.png')}}"/></label>
        {% endif %}
        <input id="file-input-right" type=file name=file onchange="mysubmit(this)"/>
        </div>
    </div>
    </form>
</div>

然后在app.py中:

@app.route('/calc_full_result', methods=['POST'])
def calc_full_result():
    if request.method == 'POST':
        file = request.files['file']
        return jsonify(result="suc")

但我无法获取目标文件,它总是空的并且无法保存。当我检查请求时,我可以看到len(request.data)几乎是图像文件的大小。 我想知道为什么request.files为空以及如何在request.data中保存文件?有可能吗?

1 个答案:

答案 0 :(得分:0)

尝试:

data: new FormData(document.getElementById('upload-form-left'))