Flask 学习-56.Flask-RESTX 开发文件(FileStorage)上传功能接口

前言

Flask-RESTX 官方文档中没提供文件上传接口示例,需结合flask 框架的文件上传功能

文件上传

RequestParser 参数校验

       parser = reqparse.RequestParser()
        parser.add_argument('file', required=True, type=FileStorage, location='files')
        parser.add_argument('title', type=FileStorage, location='files')
        args = parser.parse_args()
        file = args['file']  # 获取文件对象

默认情况下,RequestParser尝试解析来自 flask.Request.values和的值flask.Request.json。
使用location参数来add_argument() 指定从中提取值的备用位置。上的任何变量 flask.Request都可以使用。例如:

# Look only in the POST body
parser.add_argument('name', type=int, location='form')

# Look only in the querystring
parser.add_argument('PageSize', type=int, location='args')

# From the request headers
parser.add_argument('User-Agent', location='headers')

# From http cookies
parser.add_argument('session_id', location='cookies')

# From file uploads
parser.add_argument('picture', type=werkzeug.datastructures.FileStorage, location='files')

可以通过将列表传递给来指定多个参数位置location:

parser.add_argument('text', location=['headers', 'values'])

完整示例

import os
from flask import Flask, flash, request, redirect, url_for, render_template
from werkzeug.utils import secure_filename
from flask import send_from_directory
from werkzeug.datastructures import FileStorage
from flask_restx import Resource, Api, reqparse

BASE_DIR = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER = os.path.join(BASE_DIR, 'media')
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'}

api = Api()
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
api.init_app(app)


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


@api.route('/upfile')
class Upload(Resource):

    @staticmethod
    def allowed_file(filename):
        return '.' in filename and \
               filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('file', required=True, type=FileStorage, location='files')
        parser.add_argument('title', type=FileStorage, location='files')
        args = parser.parse_args()
        file = args['file']  # 获取文件对象
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)  # 校验文件名称合法
            print(filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return {
                'msg': 'success',
                'url': f'/images/{filename}/',
            }
        else:
            return {
                'msg': '文件格式不支持'
            }



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

查看图片接口参考前面这篇https://www.cnblogs.com/yoyoketang/p/16664482.html
从服务器上读取文件视图函数中使用 send_from_directory(文件的目录,文件名)来获取

from flask import send_from_directory

@app.route('/images/<filename>/')
def get_image(filename):
    return send_from_directory(UPLOAD_PATH, filename)
posted @ 2022-09-07 11:32  上海-悠悠  阅读(692)  评论(0编辑  收藏  举报