<template>
<el-upload
class="avatar-uploader"
action="http://localhost:8080/users/uploadImg"//访问后端接口
:show-file-list="false"
:on-success="handleAvatarSuccess"//上传成功后的操作,将图片进行回显
:before-upload="beforeAvatarUpload"//上传前的操作
:limit=1//限制上传数量只为一
>
<img v-if="imageUrl" :src="imageUrl" class="avatar" />
<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
</el-upload>
</template>
<script setup>
import {ref, reactive, defineComponent, computed} from "vue";
import {login,findByToken,updateMsg,uploadImg} from '../request/userApi'
import router from '../router/index'
import guide from '../components/guide.vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
const imageUrl = ref('')//图片回显值
const handleAvatarSuccess= (
res
) => {
console.log(res.data)
imageUrl.value = res.data//将图片进行回显
console.log(imageUrl.value)
}
const beforeAvatarUpload = (rawFile) => {
if (rawFile.type !== 'image/jpeg'&&rawFile.type!=='image/png') {//只能为图片类型
// imageUrl=rawFile
ElMessage.error('请选择图片类型的文件!')
return false
} else if (rawFile.size / 1024 / 1024 > 2) {
ElMessage.error('大小不能超过2MB!')//不能大于2MB
return false
}
return true
}
</script>
后端
首先创建一个配置类WebMvcConfig,配置资源映射路径
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("file:E:/spring/shop/src/main/java/com/static/");
}
}
引号处第一个地方写访问映射路径,第二处写你要存储的绝对路径
这样我们下载到这个绝对路径时,我们就可以在浏览器通过http://localhost:8080/static/
加你的文件名访问到
然后再再控制类里面写
@PostMapping("/uploadImg")
public Result uploadFile(@RequestParam("file") MultipartFile file, Model model){
String fileName = file.getOriginalFilename();
System.out.println("111"+fileName);
String suffixName = fileName.substring(fileName.lastIndexOf(".")); // 后缀名
String filePath = "E:\\spring\\shop\\src\\main\\java\\com\\static\\"; // 上传后的路径
fileName = UUID.randomUUID() + suffixName; // 新文件名
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
} catch (IOException e) {
e.printStackTrace();
}
String filename = "/static/" + fileName;
model.addAttribute("filename", filename);
System.out.println("http://localhost:8080/static/"+fileName);
return ResultUtil.success("上传图片成功","http://localhost:8080/static/"+fileName);
}
就可以了!