spring boot 图片上传

 1       /*
 2           白名单请求都直接放行:
 3          */
 4         List<String> urlList = new ArrayList<>(); 8         //对上传图片的url接口/product/img-upload的请求直接放行
 9         urlList.add("/product/img-upload");
10         //对static下的/img/upload中的静态资源图片的访问直接放行
11         if(urlList.contains(path)||path.contains("/img/upload")){
12             chain.doFilter(request, response);
13             return;
14         }
 1     /**
 2      * 上传图片的url接口/product/img-upload
 3      *
 4      * 参数MultipartFile file对象封装了上传的图片;
 5      *
 6      * @CrossOrigin表示该url接口允许跨域请求;
 7      */
 8     @CrossOrigin
 9     @PostMapping("/img-upload")
10     public Result uploadImage(MultipartFile file){
11 
12         try {
13             //拿到图片上传到的目录(类路径classes下的static/img/upload)的File对象
14             File uploadDirFile = ResourceUtils.getFile(uploadPath);
15             //拿到图片上传到的目录的磁盘路径
16             String uploadDirPath = uploadDirFile.getAbsolutePath();
17             //拿到图片保存到的磁盘路径
18             String fileUploadPath = uploadDirPath + "\\" + file.getOriginalFilename();
19             //保存图片
20             file.transferTo(new File(fileUploadPath));
21             return Result.ok("图片上传成功!");
22         } catch (Exception e) {
23             return Result.err(Result.CODE_ERR_BUSINESS,"图片上传失败!");
24         }
25     }
1 #application.properties文件
2 # 图片上传位置
3 file.upload-path=classpath:static/img/upload
4 # 上传的图片保存数据库的访问路径
5 file.access-path=/img/upload/

 

posted @ 2024-03-06 00:03  小※兽  阅读(45)  评论(0编辑  收藏  举报