python Flask文件上传第1部分

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Flask文件上传第1部分相关的知识,希望对你有一定的参考价值。

import os
from flask import Flask, render_template, request

app = Flask(__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))


@app.route('/')
def index():
    return render_template('upload.html')


@app.route('/upload', methods=['POST'])
def upload():
    target = os.path.join(APP_ROOT, 'images/')
    print(target)

    if not os.path.isdir(target):
        os.mkdir(target)

    for file in request.files.getlist('file'):
        print(file)
        filename = file.filename
        destination = '/'.join([target, filename])
        print(destination)
        file.save(destination)

    return render_template('complete.html')


if __name__ == "__main__":
    app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload</title>
</head>
<body>
<h1>File upload</h1>

<form id='upload-form' action='{{ url_for('upload')}}' method='POST' enctype='multipart/form-data'>
    <input type='file' name='file' accept="image/*" multiple>
    <input type="submit" value="send">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Complete</title>
</head>
<body>
   Voila, file uploaded!
</body>
</html>
# кастомизация имени загружаемого файла
import os
from flask import Flask, render_template, request

app = Flask(__name__)

APP_ROOT = os.path.dirname(os.path.abspath(__file__))


@app.route('/')
def index():
    return render_template('upload.html')


@app.route('/upload', methods=['POST'])
def upload():
    target = os.path.join(APP_ROOT, 'images/')
    print(target)

    if not os.path.isdir(target):
        os.mkdir(target)
    else:
        print("Couldn't create upload directory: {}".format(target))
    print(request.files.getlist('file'))
    for upload in request.files.getlist('file'):
        print(upload)
        print('{} is the file name'.format(upload.filename))
        filename = upload.filename
        destination = '/'.join([target, 'temp.jpg'])
        print('Accept incoming file:', filename)
        print('Save it to:', destination)
        upload.save(destination)

    return render_template('complete.html')


if __name__ == "__main__":
    app.run(debug=True)

以上是关于python Flask文件上传第1部分的主要内容,如果未能解决你的问题,请参考以下文章

如何在Python框架Flask中将图像文件从表单上传到数据库

16Flask实战第16天:Flask文件上传

python flask 上传多个文件,代码怎么写?

总结--flask部分

使用 Flask 和 Python 3 测试文件上传

Ajax+Python flask实现上传文件功能