FLASK 文件上传 --- 原生实现

FLASK 文件上传 --- 原生实现

使用Flask的原有的功能实现文件(图片)上传功能。


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by Flynn on 2018-08-29 14:28

import os

from flask import Blueprint
from flask import request, render_template, send_from_directory, url_for, flash
from werkzeug.utils import secure_filename

bp = Blueprint('upload1', __name__, url_prefix='/upload1/')

UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif']
MAX_CONTENT_LENGTH = 16 * 1024 * 1024  # 16MB


def is_allowed_files(filename):
    """
    判断是否是文件,以及文件格式
    :param filename:
    :return:
    """
    # 判断是否有.
    # 判断 '.' 后的文件格式是否存在可上传的文件格式中
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@bp.route('/uploads/', methods=['GET', 'POST'])
def uploaded_file(filename):
    # 第一个参数保存文件的文件夹路径
    # 第二个参数是文件名
    # 返回文件的可访问路径
    file_url = send_from_directory(UPLOAD_FOLDER, filename)
    return file_url


@bp.route('/', methods=['GET', 'POST'])
def index():
    file_url = 'uploads/logo.png'

if request.method == 'POST':
    # 从form中取得file对象
    file = request.files['file']
    length = len(file.read())
    if length > MAX_CONTENT_LENGTH:
        flash('文件太大,请重新上传!')
        return render_template('upload1/index.html')

    # 判断文件是否存在
    # 判断上传文件类型是否符合要求
    if file and is_allowed_files(file.filename):
        # 返回安全的文件名称
        # 具体解释ctrl+左键,进去看源码
        filename = secure_filename(file.filename)
        # 保存文件
        file.save(os.path.join(UPLOAD_FOLDER, filename))
        # 获得文件的可访问路径
        file_url = url_for('upload1.uploaded_file', filename=filename)
        print('file_url1 = ', file_url)  # 打印结果: /upload1/uploads/1525269617847e958494e4a.jpg
        # file_url = send_from_directory(UPLOAD_FOLDER, filename)
        # print('file_url2 = ', file_url)  # 打印结果: 
context = {}
context['file_url'] = file_url
return render_template('upload1/index.html', **context)




{% for message in get_flashed_messages() %} {{ message }} {% endfor %}

参考

https://zhuanlan.zhihu.com/p/23731819
https://juejin.im/post/5b3089c151882574e94f0864

你可能感兴趣的:(FLASK 文件上传 --- 原生实现)