直接代码以下:html
def test(): # 读取图片 image_base64 = None img_save_path = os.path.join(os.environ['BASE_PATH'], 'frontend', 'static', 'media', 'work_ticket', 'Photo.jpg') with open(img_save_path, 'rb') as f: ls_f = base64.b64encode(f.read()) image_base64 = str(base64.b64encode(ls_f), encoding='utf-8') f.close()
读取本地图片为base64基本就是上面样式了,换个路径就能够用的。前端
<img src="data:image/jpg;base64,这里是base64的编码"/>
第一个最后获得的 image_base64 这个变量就是这里的base64 编码。值得注意的是,由于在前端展现的时候,前面要加一段data:image/jpg;base64,
因此要注意base64编码,有的是直接包含这一段的,要在后端作处理,把后面的base64编码提取出来。python
mongo中有一个gridFS能够用来存储图片这些大文件。web
from pymongo import MongoClient,monitoring import base64 import gridfs # host: mongo数据库所在服务器地址 # port: mongo数据库端口 # db_name: 数据库的名称 client = MongoClient(host,port) database = client.get_database(db_name) ret = None try: fs = gridfs.GridFS(database, collection='fs') ret = fs.put(base64.b64decode(base), contentType='image/jpeg', filename='Photo.jpg') print(ret) except Exception as e: print('base64Toimg failed: %s' % e) finally: print(ret)
存储成功后,返回的ret
是mongo的默认id_id
字段值。数据库
@快乐是一切后端