Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload a file using an ajax call in flask

Tags:

python

ajax

flask

People also ask

Can we upload file using AJAX?

File upload is not possible through AJAX. You can upload file, without refreshing page by using IFrame .

How do I upload files to my Flask?

Python for web development using Flask Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to 'multipart/form-data', posting the file to a URL. The URL handler fetches file from request. files[] object and saves it to the desired location.


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:

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

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.


    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)