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)