一、从前端接收图片对象,将其转换为base64
第一种:(直接写入图片本地路径)
1 image_path = 'C:\Users\Administrator\Desktop\test2.jpg' 2 with open(image, 'rb') as f: 3 image = f.read() 4 image_base64 = str(base64.b64encode(image), encoding='utf-8')
第二种:(从页面form传入图片)
1 image = request.FILES.get('product_img', '') 2 if image: 3 image_byte = image.read() 4 # 将byte转换成str,再转换成base64,去掉首部 5 image_base64 = str(base64.b64encode(image_byte))[2:]
二、前端上传图片base64,后台保存图片
1 # 前端上传的base64,存放在django的媒体文件库中 2 if avatar_url: 3 b64_data = avatar_url.split(';base64,')[1] 4 data = base64.b64decode(b64_data) 5 image_url = os.path.join(MEDIA_ROOT_OLD, 'common/head_img/%s.jpg' % int(time.time())) 6 with open(image_url, 'wb') as f: 7 f.write(data) 8 # 截取media路径,存放在字段中 9 image_url = image_url.split("project_name")[1].replace('\', '/')[1:] 10 # user对象 11 user.avatar_url = image_url