我已經想出瞭如何使用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);
任何幫助?謝謝。
如果你想返回數組,需要轉換爲JSON和不發送任何HTML模板....只是JSON字符串 – charlietfl
因此,像jsonify(文件名)?如何通過Javascript識別正在發送的內容並更改
標籤以匹配? – quantumtremor優秀的代碼!幫助我完成我的項目。 – Aspen