Flask对接mongo上载文件

from bson import ObjectId
from flask import Flask, render_template, request, Response
from gridfs import GridFS
from pymongo import MongoClient

app = Flask(__name__)
client = MongoClient('localhost', 27017)
db = client.media
gfs = GridFS(db)


@app.route('/hello')
def hello_world():
    return 'Hello World!'


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


@app.route('/upload', methods=['POST'])
def upload():
    file = request.files.get("file")
    file_name = file.filename
    data = file.read()
    file.save('static/' + file_name)
    content_type = file.content_type
    insertimg = gfs.put(data, content_type=content_type, filename=file_name)
    return str(insertimg)


@app.route('/download', methods=['GET'])
def readfile():
    img_id = request.args.get('id')
    file = gfs.get(ObjectId(img_id))
    response = Response(file.read(), content_type='image/jpeg')
    return response


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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值