springboot+vue+elementUI实现上传头像并显示
时间: 2023-09-11 20:06:25 浏览: 142
1. 前端页面
在前端页面中,使用ElementUI组件实现上传头像的功能。首先需要引入ElementUI组件库和axios库,用于发送请求。然后在Vue实例中定义一个data对象,用于存储上传头像的相关信息。
```html
<template>
<div>
<el-upload
class="avatar-uploader"
action="/api/upload"
:show-file-list="false"
:on-success="handleUploadSuccess"
:before-upload="beforeAvatarUpload"
>
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</div>
</template>
<script>
import axios from 'axios'
import { Message } from 'element-ui'
export default {
data() {
return {
imageUrl: '',
uploadUrl: '/api/upload'
}
},
methods: {
beforeAvatarUpload(file) {
const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
if (!isJPG) {
Message.error('上传头像图片只能是 JPG 或 PNG 格式!')
}
const isLt2M = file.size / 1024 / 1024 < 2
if (!isLt2M) {
Message.error('上传头像图片大小不能超过 2MB!')
}
return isJPG && isLt2M
},
handleUploadSuccess(response, file) {
this.imageUrl = URL.createObjectURL(file.raw)
this.$emit('update:avatar', this.imageUrl)
}
}
}
</script>
```
上述代码中,使用了`<el-upload>`组件实现上传头像的功能。其中,`action`属性指定了上传头像的接口地址,`show-file-list`属性为false表示不显示上传文件列表,`on-success`属性指定了上传成功后的回调函数,`before-upload`属性指定了上传前的校验函数。
在`beforeAvatarUpload`函数中,对上传的文件进行格式和大小的校验,如果不符合要求则提示用户。如果校验通过,则返回true,表示可以上传。
在`handleUploadSuccess`函数中,获取上传成功后服务器返回的图片地址,将其赋值给`imageUrl`变量,然后使用`URL.createObjectURL`方法创建一个临时的Object URL,将其赋值给`imageUrl`变量,用于在页面中显示头像。
2. 后端接口
在后端接口中,使用SpringBoot框架实现上传头像的功能。首先需要在Controller中添加一个接口,用于接收上传的头像文件。
```java
@RestController
@RequestMapping("/api")
public class UploadController {
@Autowired
private Environment env;
@PostMapping("/upload")
public Map<String, Object> upload(MultipartFile file) throws Exception {
String fileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(file.getOriginalFilename());
String filePath = env.getProperty("spring.servlet.multipart.location") + fileName;
File dest = new File(filePath);
file.transferTo(dest);
Map<String, Object> map = new HashMap<>();
map.put("url", "/uploads/" + fileName);
return map;
}
}
```
上述代码中,使用了`@PostMapping`注解指定了上传头像的接口地址为`/api/upload`,使用了`@Autowired`注解注入了`Environment`对象,用于获取上传文件的保存路径。在`upload`方法中,首先生成一个随机的文件名,然后将上传的文件保存到指定的路径中。
最后将上传成功后的文件路径返回给前端页面。
3. 图片显示
通过前面的步骤,已经实现了上传头像的功能,并将上传成功后的图片路径返回给前端页面。现在需要将图片显示在页面中。
在Vue实例中,使用`imageUrl`变量存储上传成功后的图片路径。然后将该变量绑定到`<img>`标签的`src`属性上,用于显示上传的头像。
```html
<img v-if="imageUrl" :src="imageUrl" class="avatar">
```
如果上传的头像图片比较大,可能会造成页面加载缓慢,影响用户体验。为了提高页面加载速度,可以使用懒加载的方式加载图片,只有当图片进入可视区域时才进行加载。
Vue提供了`v-lazy`指令,可以实现图片的懒加载。只需要将`v-lazy`指令绑定到`<img>`标签的`src`属性上,然后在`<img>`标签上添加一个`lazy`类,就可以实现图片的懒加载。
```html
<img v-if="imageUrl" v-lazy="imageUrl" class="avatar lazy">
```