flask-restful编写上传图片api

flask-restful编写上传图片api

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

引入FileStorage

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

1
2
3
4
5
6
7
8
9
10
11
12
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.

1
2
3
4
5
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`.

完整代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/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()

flask-restful编写上传图片api

https://www.huihuidehui.com/posts/9e5a0e91.html

作者

辉辉的辉

发布于

2020-03-16

更新于

2020-03-16

许可协议

评论