问题描述
喜恩很新的烧瓶中,我不会使用Ajax调用服务器上传文件。正如前面提到的文档中我添加了一个文件上传到HTML作为folows
Hi um quite new to flask and I wont to upload a file using a ajax call to the server. As mentioned in the documentation I added a file upload to the html as folows
<form action="" method=post enctype="multipart/form-data" id="testid">
<table>
<tr>
<td>
<label>Upload</label>
</td>
<td>
<input id="upload_content_id" type="file" name="upload_file" multiple>
<input type="button" name="btn_uplpad" id="btn_upload_id" class="btn-upload" value="Upload"/>
</td>
</tr>
</table>
</form>
和我写的AJAX处理程序,因为这
and I wrote the ajax handler as this
$(document).ready(function() {
$("#btn_upload_id" ).click(function() {
$.ajax({
type : "POST",
url : "/uploadajax",
cache: false,
async: false,
success : function (data) {},
error: function (XMLHttpRequest, textStatus, errorThrown) {}
});
});
});
我不知道如何从这种获取上传的文件(而不是名称) 并保存在文件中的文件夹。嗯不太清楚如何读取处理我所写入的文件
I do not know how to get the uploaded file(not the name) from thisand save the file in folder. Um not quite sure how to read the file from handler which i have written
@app.route('/uploadajax', methods = ['POST'])
def upldfile():
if request.method == 'POST':
file_val = request.files['file']
我会很感激,如果有人可以提供帮助。谢谢你在前进
I will be grateful if anyone can help. Thank you in advance
推荐答案
要回答你的问题...
To answer your question...
HTML:
<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>
</form>
JavaScript的:
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!');
},
});
});
});
现在在瓶中的端点观点功能,您可以通过flask.request.files访问文件的数据。
Now in your flask's endpoint view function, you can access the file's data via flask.request.files.
在一个侧面说明,形式不是表格数据,因此它们不属于一个表。相反,你应该采取一个无序列表,或定义列表。
On a side note, forms are not tabular data, therefore they do not belong in a table. Instead, you should resort to an unordered list, or a definition list.
这篇关于如何用瓶Ajax调用要上传的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!