前端:
<el-upload
class="avatar-uploader"
action="#"
:show-file-list="false"
:auto-upload="false"
:on-change="updateEdit"
:before-upload="beforeAvatarUpload">
<el-button style="margin-left: 10px" size="small" type="success">
<i class="el-icon-upload"></i>更换头像</el-button>
</el-upload>
const updateEdit = (file: any) => {
const image = new Image()
image.src = URL.createObjectURL(file.raw)
image.onload = async () => {
const canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
const context = canvas.getContext('2d')
context.drawImage(image, 0, 0, image.width, image.height)
updheaderimg.header_img = canvas.toDataURL() //图片的base64地址
const res = await Service.Updheaderimg({ ...updheaderimg })
getcurrentuser()
}
updheaderimg.filename = file.name
updheaderimg.uid = file.uid
}
后端:
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
try:
header_img=b['header_img']
b64_data = header_img.split(';base64,')[1]
car_image = base64.b64decode(b64_data)
suffix = b['filename'].split('.')[1]
picName = str(b['uid']) + '.' + suffix
path = os.path.join(settings.BASE_DIR, r"static\headerImage\%s" %(picName))
file = open(path, 'wb')
file.write(car_image)
file.close()
UserModel.objects.filter(id=id).update(header_img=picName)