1. Front-end vue code, upload the avatar picture and display it, click the button to send it to the back-end
<template>
<div @click="toGetImg">
<img v-if="uploadImg" :src="uploadImg" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过2MB!</div>
<el-button type="primary" @click="saveAvatar">上传并保存</el-button>
</div>
</template>
<script>
let inputElement = null
export default {
data() {
return {
uploadImg: null,
};
},
methods: {
toGetImg() {
if (inputElement === null) {
// 生成文件上传的控件
inputElement = document.createElement('input')
inputElement.setAttribute('type', 'file')
inputElement.style.display = 'none'
if (window.addEventListener) {
inputElement.addEventListener('change', this.uploadFile, false)
} else {
inputElement.attachEvent('onchange', this.uploadFile)
}
document.body.appendChild(inputElement)
}
inputElement.click()
},
uploadFile(el) {
if (el && el.target && el.target.files && el.target.files.length > 0) {
const files = el.target.files[0]
const isLt2M = files.size / 1024 / 1024 < 2
const size = files.size / 1024 / 1024
// 判断上传文件的大小
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!')
} else if (files.type.indexOf('image') === -1) { //如果不是图片格式
// this.$dialog.toast({ mes: '请选择图片文件' });
this.$message.error('请选择图片文件');
} else {
const that = this;
const reader = new FileReader(); // 创建读取文件对象
reader.readAsDataURL(el.target.files[0]); // 发起异步请求,读取文件
reader.onload = function () { // 文件读取完成后
// 读取完成后,将结果赋值给img的src
that.uploadImg = this.result;
console.log(that.uploadImg)
// 数据传到后台
// const formData = new FormData()
// formData.append('file', files); // 可以传到后台的数据
};
}
}
},
saveAvatar() {
const base64String = this.uploadImg;
//这里对base64串进行操作,去掉url头,并转换为byte
const bytes = window.atob(base64String.split(',')[1]);
const ab = new ArrayBuffer(bytes.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) {ia[i] = bytes.charCodeAt(i);}
const blob = new Blob([ab], {type: 'image/jpeg'})
const formData = new FormData()
formData.append('file', blob, Date.now() + '.jpg');
console.log(formData)
this.axios.post('http://127.0.0.1:668/saveAvatar', formData).then(res => {
})
},
},
beforeDestroy() {
if (inputElement) {
if (window.addEventListener) {
inputElement.removeEventListener('change', this.onGetLocalFile, false)
} else {
inputElement.detachEvent('onchange', this.onGetLocalFile)
}
document.body.removeChild(inputElement)
inputElement = null
console.log('inputelement destroy')
}
}
};
</script>
<style>
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
border: 1px dashed;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
2. The python backend receives the picture and saves it
def saveAvatar():
upload_file = request.files['file']
print(upload_file)
filename = 'admin.jpg'
filepath = os.path.join('./static/avatar', filename)
upload_file.save(filepath)