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/
本文作者:小※兽
本文链接:https://www.cnblogs.com/dsds/p/18055607
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步