File upload with Flask + jQuery

I haven't studied Python itself properly, so the code may be that.

environment

code

If you run run.py with the following code and upload the file, the uploaded file will be placed in the same hierarchy as run.py.

run.py


from flask import Flask, request
app = Flask(__name__)

@app.route('/upload', methods=['POST'])
def upload():
    the_file = request.files['the_file']
    the_file.save("./" + the_file.filename)
    print request.form['other_data']    # 999
    return ""

if __name__ == '__main__':
    app.run()

index.html


<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Flask Upload Test</title>
</head>
<body>
<button>Upload File</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
    (function () {
        'use strict';

        var onClickButton = function () {
            var html =
                    '<form id="uploadForm" class="upload-form" style="display: none;">' +
                    '<input id="theFile" name="the_file" type="file">' +
                    '</form>';
            $('body').append(html);
            $('#theFile').on('change', uploadFile).click();
        };

        var uploadFile = function () {
            var formData = new FormData($('#uploadForm')[0]);
            formData.append('other_data', 999);
            $.ajax({
                url: '/upload',
                type: 'post',
                data: formData,
                processData: false,
                contentType: false,
                timeout: 10000
            }).done(function () {
                console.log('done');
            }).fail(function () {
                console.log('fail');
            }).then(function () {
                $('#uploadForm').remove();
            });

        };

        $('button').on('click', onClickButton);
    })();
</script>
</body>
</html>

Recommended Posts

File upload with Flask + jQuery
File upload with django
Image upload function with Vue.js + Flask
Upload files with Django
File operations with open — "../"
IP restrictions with Flask
Hello world with flask
Programming with Python Flask
How to upload with Heroku, Flask, Python, Git (Part 1)
How to upload with Heroku, Flask, Python, Git (Part 2)
Deploy Flask with ZEIT Now
Touch Flask + run with Heroku
Hello World with Flask + Hamlish
Unit test flask with pytest
API with Flask + uWSGI + Nginx
SNS Flask (Ajax) made with Flask
Web application development with Flask
Upload a file to Dropbox
Fast file transfer with fabric
Image upload & customization with django-ckeditor
Bidirectional file transfer with Pythonista 3
View flask coverage with pytest-cov
Web application with Python + Flask ② ③
Download csv file with python
Create xlsx file with XlsxWriter
Upload multiple files in Flask
Web application with Python + Flask ④
Upload file to GCP's Cloud Storage (GCS) ~ Load with local Python
SNS Flask (Model) edition made with Flask
[LINE login] Verify state with Flask
Let's upload S3 files with CLI
Extract the xz file with python
Get video file information with ffmpeg-python
SNS Python basics made with Flask
[Python] Write to csv file with Python
[Automation with python! ] Part 1: Setting file
Implemented file download with Python + Bottle
[Memo] Links for developing with Flask
Follow the file hierarchy with fts
Output to csv file with Python
Run the app with Flask + Heroku
Persist Flask API server with forever
Serve static files with X-Send File
[Python] Use Basic/Digest authentication with Flask
Create an Excel file with Python3
Output cell to file with Colaboratory
Upload & move GCS files with Go
Basic authentication and Digest authentication with Flask
Creating a simple app with flask
Build Flask environment with Dockerfile + docker-compose.yml
SNS made with Flask Flask (Blueprint, bcrypt)
Download the file deployed with appcfg.py
Use camera calibration file with OpenCvSharp4
[Automation with python! ] Part 2: File operation
Open the file with the default app
Post bulletin board creation with flask
Configuration file best practices in Flask
Application development with Docker + Python + Flask
Upload and download images with falcon
File upload to Azure Storage (Python)
Create a file uploader with Django