11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Flask + jQueryでファイルアップロード

Last updated at Posted at 2015-09-03

Python自体ちゃんと勉強してませんのでコードがアレかも。

環境

  • Python 2.7.10
  • Flask 0.10.1

コード

以下のコードでrun.pyを走らせて、ファイルをアップロードすると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>
11
13
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?