上传图片
element页面代码springboot页面代码 展示图片
element页面代码springboot页面代码
流程简介:前端页面使用element自带的el-upload标签上传文件,后端获取文件绝对路径后将图片上传到服务器,再将服务器存储的绝对路径映射为url路径(前端页面无法直接使用绝对路径打开,所以必须将绝对路径转为url路径才可展示文件)
springboot页面代码 将文件拖到此处,或点击上传只能上传jpg/png文件,且不超过500kb
@RestController
@RequestMapping(value = "/api/mainadmin" ,produces = "application/json;charset=UTF-8")
public class FileController {
@PostMapping(value = "/fileUpload")
public String fileUpload(@RequestParam(value = "file")MultipartFile file){
if (file.isEmpty()){
return"空文件";
} else {
String fileName = file.getOriginalFilename(); //文件名
String suffixName = fileName.substring(fileName.lastIndexOf(".")); //后缀名
String filePath = "D://ych//img//user//"; //存储路径
fileName = UUID.randomUUID().toString().replace("-","")+suffixName; //新文件名
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()){
dest.getParentFile().exists();
}
try {
file.transferTo(dest);
}catch (IOException e){
e.printStackTrace();
}
String filename = "/test_img/"+fileName;
System.out.println(filename);
return filename;
}
}
}
展示图片
element页面代码
springboot页面代码
通过配置文件将本地路径转为url访问的网络路径
@Configuration
public class MyWebMvcConfigurer implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/test_img/**")
.addResourceLocations("file:D://ych//img//user//");
}
}



