restful get不传参数404_flask-restful编写上传图片api

7d1ee9e7aee8037b588812cf8156c932.png

Flask-RESTful是用于快速构建REST API的Flask扩展。我最近在使用Flask-Restful + Vue.js写一个轻量博客时有一个前端后端上传图片的需求。在Flask-Restful的官方文档中并没有相关的内容。下面是我谷歌查找资料的总结。

引入FileStorage

flask-restful的参数解析中并没有文件类型,需要引入werkzeug.datastructures.FileStorage作为参数解析中的类型。上传图片的资源api可以这样编写:

class UploadImg(Resource):
    def __init__(self):
        # 创建一个新的解析器
        self.parser = reqparse.RequestParser()
        # 增加imgFile参数,用来解析前端传来的图片。
        self.parser.add_argument('imgFile', required=True, type=FileStorage,location='files',help="imgFile is wrong.")

    def post(self):
        img_file = self.parser.parse_args().get('imgFile')
        # 保存图片
        img_file.save(img_file.filename)
        return 'ok', 201

FileStorage这个类有很多的内置方法,这里使用了save方法保存了图片,save方法接受两个参数源码里面说明如下:dst指定保存文件的name.

def save(self, dst, buffer_size=16384):
  :param dst: a filename, :class:`os.PathLike`, or open file
            object to write to.
        :param buffer_size: Passed as the ``length`` parameter of
            :func:`shutil.copyfileobj`.

完整代码

#!/usr/bin/env python
# encoding: utf-8
from flask_restful import reqparse, Resource, Api
from werkzeug.datastructures import FileStorage
from flask import Flask


class UploadImg(Resource):
    def __init__(self):
        # 创建一个新的解析器
        self.parser = reqparse.RequestParser()
        # 增加imgFile参数,用来解析前端传来的图片。
        self.parser.add_argument('imgFile', required=True, type=FileStorage,location='files',help="imgFile is wrong.")

    def post(self):
        img_file = self.parser.parse_args().get('imgFile')
        img_file.save(img_file.filename)
        return 'ok', 201


if __name__ == '__main__':
    app = Flask(__name__)
    api = Api(app)
    api.add_resource(UploadImg, '/uploadimg')
    app.run()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值