2013-11-28 33 views
3

我已經想出瞭如何使用AJAX和Flask上傳文件,以便頁面不刷新並且文件上載到服務器在某個指定的目錄中。 在Python方法(upload())中,我想用一些正則表達式處理文件名,並將數組返回給Javascript文件。 即使我試圖請求一個數組,我仍然返回render_template(index.html)嗎?使用AJAX上傳文件,處理並使用Flask將結果返回給Javascript

HTML(的index.html)

<form id="upload-file" role="form" action="sendQuestions" method="post" enctype="multipart/form-data"> 
    <div class="modal-body"> 
     <label for="file"><b>Upload packet here</b></label> 
     <input type="file" name="file"> 
     <p class="help-block">Upload a .pdf or .docx file you want to read.</p> 
    </div> 
    <div class="modal-footer"> 
     <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
     <button id="upload-file-btn" type="button" class="btn btn-primary" data-dismiss="modal" value="Upload">Upload</button> 
    </div> 
</form> 

的Javascript

$(function() { 
    $('#upload-file-btn').click(function() { 
     var form_data = new FormData($('#upload-file')[0]); 
     $.ajax({ 
      type: 'POST', 
      url: '/uploadajax', 
      data: form_data, 
      contentType: false, 
      cache: false, 
      processData: false, 
      async: false, 
      success: function(data) { 
       console.log('Success!'); 
      }, 
     }); 
    }); 
}); 

的Python(瓶)

@app.route('/uploadajax', methods=['POST']) 
def upload(): 
    file = request.files['file'] 

    if file and allowed_file(file.filename): 
     filename = secure_filename(file.filename) 
     file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename)) 

    return render_template('index.html') 

我玩弄後加入的JavaScript本AJAX調用$ .ajax {}部分,但是我做對了嗎?我不確定是否可以在一個Javascript函數中調用同一個Python方法兩次,或者是否有完全更好的方法來執行此操作。

ajaxRequest = ajaxFunction() 
    ajax.onreadystatechange = function() { 
     if (ajaxRequest.readyState === 4) { 
      if (ajaxRequest.status === 200) { 
       alert(ajaxRequest.responseText) //I want the Python to put the array into this ajaxRequest.responseText variable, not sure how. 
      } 
      else 
       alert('Error with the XML request.') 
     } 
    } 
    ajaxRequest.open("GET", 'uploadajax', true); 
    ajaxRequest.send(null); 

任何幫助?謝謝。

+0

如果你想返回數組,需要轉換爲JSON和不發送任何HTML模板....只是JSON字符串 – charlietfl

+0

因此,像jsonify(文件名)?如何通過Javascript識別正在發送的內容並更改

標籤以匹配? – quantumtremor

+0

優秀的代碼!幫助我完成我的項目。 – Aspen

回答

2

你不說你想達到什麼(隱藏一些div,滾動窗口......),這是一個主要問題。綜上所述應該做什麼:
不要返回

return render_template('index.html') 

但FE。如果你要通知上傳狀態的用戶,進行狀態該呼叫像

return Response('OK') 

或其他身份 - NOTOK什麼的。 然後在JS:

success: function(data) { 
     console.log('Success!'); 
    }, 

操縱響應

if (data == 'OK') { 
    alert ('YAY, FILE UPLOADED'); 
}; 
+0

對不起。我使用re.findall()從PDF生成列表,然後我想將列表返回給Javascript。 – quantumtremor

+1

好的。所以你只需在字典中收集數據。然後返回jsonify(this_dict),並在上傳成功部分使用它。 –

+0

這很棒! – Aspen

相關問題