如何在flask中使用ajax调用上传文件 [英] How to upload a file using an ajax call in flask

查看:34
本文介绍了如何在flask中使用ajax调用上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Flask 很陌生,我想使用 ajax 调用将文件上传到服务器.正如文档中提到的,我添加了一个文件上传到 html 如下:

Hi I'm quite new to flask and I want to upload a file using an 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 this

  <input id="upload_content_id" type="file" name="upload_file" multiple>

并将文件保存在文件夹中.我不太确定如何从我编写的处理程序中读取文件:

and save the file in folder. I'm 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

推荐答案

回答你的问题...

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,
            success: function(data) {
                console.log('Success!');
            },
        });
    });
});

现在在您的flask 的端点视图函数中,您可以通过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.

这篇关于如何在flask中使用ajax调用上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆