2015-08-24 54 views
-1

我想通過JQuery中的AJAX將文件上傳到我的Flask後端。Flask中的文件上傳 - 400錯誤請求

我的Python側面看起來是這樣的:

@app.route('/upload/', methods=['POST', 'GET']) 
def upload(): 
    if request.method == 'GET': 
     return render_template('uploadfile.html') 
    elif request.method == 'POST': 
     file_val = request.files['file'] 
     return 'it worked!' 

需要注意的是,當我做形式的正常工作提交。

我的HTML和AJAX看起來是這樣的:

<form id="upload-file" method="post" enctype="multipart/form-data"> 
<fieldset> 
    <label for="file">Select a file</label> 
    <input name="file" type="file"> 
</fieldset> 
<fieldset> 
    <button id="upload-file-btn" type="button">Upload</button> 
</fieldset> 

$(document).on("click", "#upload-file-btn", function() { 
    var form_data = new FormData($('#input-file')[0]); 
    $.ajax({ 
     type: 'POST', 
     url: '/upload/', 
     data: form_data, 
     contentType: false, 
     cache: false, 
     processData: false, 
     async: false, 
     success: function(data) { 
      alert("UREKA!!!"); 
     }, 
     error: function(jqXHR, textStatus, errorThrown) { 
      console.log(jqXHR); 
      console.log(textStatus); 
      console.log(errorThrown); 
     } 
    }); 

    return false; 
}); 

然而,在執行AJAX請求時,我得到一個400響應。我認爲這是與contentType有關,但真的很感謝任何指導:)

+0

確實瓶本身說什麼? (正在調試?) – Sevanteri

回答

1

我沒有看到任何與此ID的元素$('#input-file'),我的猜測要麼你想有窗體的ID或只是input[type="file"]'的身份證。

你可以試試這個:

var form_data = new FormData($('input[type="file"]')[0]);