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)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章