How to upload a file using an ajax call in flask

后端 未结 3 1275
无人及你
无人及你 2020-11-30 00:14

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:

相关标签:
3条回答
  • 2020-11-30 00:37

    Its there in the tutorial.

    from flask import send_from_directory
    
    @app.route('/uploads/')
    def uploaded_file(filename):
        return send_from_directory(app.config['UPLOAD_FOLDER'],
                                   filename)
    

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

    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.

    0 讨论(0)
  • 2020-11-30 00:40
        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)
    
    0 讨论(0)
  • 2020-11-30 00:46

    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.

    0 讨论(0)
提交回复
热议问题