简易的springboot上传头像(图片)代码片段

傷城~ 2023-05-29 05:29 78阅读 0赞
  1. /** * 上传头像 * * @throws IOException * @throws IllegalStateException */
  2. public String upload(MultipartFile file) throws IllegalStateException, IOException {
  3. File dir = new File(rootpath);
  4. if (!dir.exists()) {
  5. dir.mkdirs();
  6. }
  7. //读取文件名
  8. String fileName = file.getOriginalFilename();
  9. if (!StringUtil.isEmpty(fileName)) {
  10. //获取文件的后缀
  11. String suffix = FilenameUtils.getExtension(fileName);
  12. //UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法,生成唯一的标识
  13. //修改后的文件名(带后缀)
  14. String newFileName = UUID.randomUUID().toString().toLowerCase() + "." + suffix;
  15. //public File(File parent, String child)--->dir就是相当于这个文件的路径(不包含这个文件的文件名),newFileName指的是文件名;
  16. File targetFile = new File(dir, newFileName);
  17. //将文件提交到目的地文件系统中
  18. file.transferTo(targetFile);
  19. System.out.println(newFileName + "mmm");
  20. //图片上传以后,“\\”要变成“/”、而且前面的根路径也不需要了;
  21. String imgpath = targetFile.getPath().replace("\\", "/").replace(rootpath, "");
  22. System.out.println(imgpath);
  23. return imgpath;
  24. } else {
  25. return null;
  26. }
  27. }

发表评论

表情:
评论列表 (有 0 条评论,78人围观)

还没有评论,来说两句吧...

相关阅读

    相关 头像,背景图片详解

    头像,背景图片上传详解 上传头像和上传背景图片的思路都是一样的,所以这里选讲一下上传头像就行。 上传头像页面样式: ![在这里插入图片描述][watermark_