Veu+ElementPlus+SpringBoot实现图片上传功能
Veu+ElementPlus+SpringBoot实现图片上传功能
文件上传
后端
在application中设置一个存放图片的路径Path:如我的路径为D:\local_image\bigTypeImgs
bigTypeImagesFilePath: D://local_image/bigTypeImgs/
后端请求
@Value("${bigTypeImagesFilePath}")
private String bigTypeImagesFilePath;//将存放路径注入到bigTypeImagesFilePath中
@RequestMapping("/uploadImage")
public Map<String,Object> uploadImage(MultipartFile file) throws Exception{
Map<String,Object> resultMap =new HashMap<>();
if(!file.isEmpty()){
//上传的文件是否为空
String filename = file.getOriginalFilename();//获取原始的文件名
//filename.lastIndexOf(".")是获取最后一个点的索引,substring是自索引(包括当前索引)以后的字符串进行截取
String suffixName = filename.substring(filename.lastIndexOf("."));//获得当前位置的后缀
//DateUtil.getCurrentDateStr()是获取当前事件日期格式
//将当前日期和后缀
String newFileName= DateUtil.getCurrentDateStr()+suffixName;//拼接一个新的文件名
//copyInputStreamToFile将一个输入流的内容拷贝到某个文件,第二个参数是文件路劲与文件名
FileUtils.copyInputStreamToFile(file.getInputStream(),new File(bigTypeImagesFilePath+newFileName));
resultMap.put("code",0);
resultMap.put("msg","上传成功");
Map<String,Object> dataMap =new HashMap<>();
dataMap.put("title",newFileName);//返回文件名
dataMap.put("src","/image/bigType/"+newFileName);//回显路劲
resultMap.put("data",dataMap);
}
return resultMap;
}
编写配置类,方便图片映射本地:
@Configuration
public class WebAppConfigurer implements WebMvcConfigurer {
/**
* 处理跨域问题
* @param registry
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE","OPTIONS")
.maxAge(3600);
}
//重写资源处理的方法
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//添加资源处理程序
registry.addResourceHandler("/image/bigType/**").addResourceLocations("file:D:\\local_image\\bigTypeImgs\\");
}
}
前端
子组件
<script setup>
import {
ref} from "vue";
import {
Delete, Edit, Search} from '@element-plus/icons-vue'
import axios from "axios";
import axiosUtil,{
getServeUrl} from '@/util/axios'
import Dialog from "./components/dialog";
import {
ElMessage, ElMessageBox} from "element-plus";
import ImageDialog from