vue3仿抖音上传头像
时间: 2023-07-18 16:41:56 浏览: 59
实现仿抖音上传头像的方式可以分为以下几个步骤:
1. 创建一个包含上传组件的 Vue 组件。
2. 在组件中引入 `vue-cropperjs` 插件,用于剪裁图片。
3. 在组件中引入 `axios` 模块,用于上传图片。
4. 在组件中定义一个 `file` 变量,用于存储选择的文件。
5. 在模板中添加一个 `input[type=file]` 元素,用于选择文件。
6. 在选择文件后,将文件赋值给 `file` 变量。
7. 在模板中添加一个按钮,用于触发剪裁图片的操作。
8. 在剪裁完成后,将剪裁后的图片转换为文件格式,并通过 `axios` 模块上传到服务器。
以下是一个示例代码:
```
<template>
<div>
<input type="file" @change="selectFile">
<button @click="uploadAvatar">上传头像</button>
<cropper v-if="file" :src="file" :guides="false" :view-mode="2" @ready="onReady" ref="cropper"></cropper>
</div>
</template>
<script>
import axios from 'axios';
import 'cropperjs/dist/cropper.css';
import VueCropper from 'vue-cropperjs';
export default {
components: {
cropper: VueCropper,
},
data() {
return {
file: null,
cropper: null,
};
},
methods: {
selectFile(e) {
this.file = e.target.files[0];
},
onReady() {
this.cropper.setAspectRatio(1);
},
async uploadAvatar() {
const canvas = this.cropper.getCroppedCanvas({
width: 200,
height: 200,
});
const blob = await new Promise(resolve => {
canvas.toBlob(blob => resolve(blob));
});
const formData = new FormData();
formData.append('avatar', blob);
await axios.post('/api/avatar', formData);
},
},
};
</script>
```
在这个示例中,我们引入了 `vue-cropperjs` 插件来实现图片剪裁的功能,使用 `axios` 模块来上传图片。在模板中添加了一个 `input[type=file]` 元素和一个上传按钮。在选择文件后,将文件赋值给 `file` 变量。在上传头像的方法中,使用 `getCroppedCanvas` 方法获取剪裁后的画布,并将其转换为文件格式进行上传。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)