我已经弄清楚如何使用AJAX和Flask上传文件,使页面不刷新,文件上传到某个指定目录的服务器 . 在Python方法(upload())中,我想用一些正则表达式处理文件名并将数组返回到Javascript文件 . 即使我正在尝试请求数组,我仍然会返回render_template(index.html)吗?
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')
我正在玩$ .ajax {}部分之后在Javascript中添加这个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);
有帮助吗?谢谢 .
1 回答
你不是一个主要问题 . 总结应该做什么:
不要回来
但是,fe . 如果您想通知用户有关上传状态的信息,请为此通话设置状态
或其他状态 - NOTOK或其他东西 . 然后在js中:
操纵响应