【发布时间】:2013-12-13 22:12:52
【问题描述】:
我已经弄清楚如何使用 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);
有什么帮助吗?谢谢。
【问题讨论】:
-
如果你想返回数组,需要转换成json并且不发送任何模板html....只是json字符串
-
像 jsonify(filename) 这样的东西?如何让 Javascript 识别正在发送的内容并更改 标记以匹配?
-
优秀的代码!帮助我完成了我的项目。
标签: javascript jquery python ajax flask