Python 如何在flask中使用ajax调用上传文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18334717/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:30:19  来源:igfitidea点击:

How to upload a file using an ajax call in flask

pythonajaxflask

提问by co2f2e

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:

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

<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>

and I wrote the ajax handler as this

我写了这样的ajax处理程序

$(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

如果有人可以提供帮助,我将不胜感激。先感谢您

采纳答案by user2588

To answer your question...

要回答你的问题...

HTML:

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!');
            },
        });
    });
});

Now in your flask's endpoint view function, you can access the file's data via flask.request.files.

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

附带说明一下,表单不是表格数据,因此它们不属于表格。相反,您应该求助于无序列表或定义列表。

回答by user2588

Its there in the tutorial.

它在教程中

从烧瓶导入 send_from_directory

@app.route('/上传/')
定义上传_文件(文件名):
    返回 send_from_directory(app.config['UPLOAD_FOLDER'],
                               文档名称)

You can return the same to a POST request. And then the AJAX success function can be used to display the response.

您可以将相同的内容返回到 POST 请求。然后可以使用 AJAX 成功函数来显示响应。

But for any practical purpose, it might be a good idea to save the file name with its associated resource in a database relationship table.

但出于任何实际目的,将文件名及其关联资源保存在数据库关系表中可能是个好主意。

回答by u10833336

    in the  Javascript side::::        

    var form_data = new FormData();
    form_data.append('file', $('#uploadfile').prop('files')[0]);

    $(function() {
    $.ajax({
        type: 'POST',
        url:  '/uploadLabel',
        data: form_data,
        contentType: false,
        cache: false,
        processData: false,
        success: function(data) {
            console.log('Success!');
        },
    });



in the server side::::


@app.route('/uploadLabel',methods=[ "GET",'POST'])
def uploadLabel():
    isthisFile=request.files.get('file')
    print(isthisFile)
    print(isthisFile.filename)
    isthisFile.save("./"+isthisFile.filename)