小言_互联网的博客

Springboot在新增和修改下上传图片并显示

327人阅读  评论(0)

解决的问题:

     本篇文章除了解决上传图片并显示的问题,还有就是在新增和修改下的图片上传如何处理。在这里新增和修改的页面是同一页面,修改的时候,将会把值带过去,但是由于类型为file的input标签是不能给其赋值的,那么若不改变原来图片,但是input标签中又没有值,这时怎么处理呢?

一 运行环境

开发工具:IDEA

后端:Springboot+JPA

前端:thymeleaf+semantic UI

二 代码实现

    springboot中已经内嵌了上传图片的依赖包,因此不需要再添加额外依赖。

1 前端页面


  
  1. <form id="blog-form" action="#" th:object="${blog}" th:action="@{/admin/blogs}" method="post" enctype="multipart/form-data" class="ui form">
  2. <!--该部分内容省略,以下为重点-->
  3. <div class="required field">
  4. <div class="ui left labeled input">
  5. <label class="ui teal basic label">首图 </label>
  6. <img src="" th:src="@{*{firstPicture}}" alt="" style="width: 500px !important;">
  7. <!-- 不能给input type="file"文件赋值-->
  8. <input type="file" name="picture">
  9. <!--<input type="text" name="firstPicture" th:value="*{firstPicture}" placeholder="首图引用地址">-->
  10. </div>
  11. </div>
  12. <!--该部分内容省略,以上为重点-->
  13. <div class="ui right aligned container">
  14. <button type="button" class="ui button" onclick="window.history.go(-1)">返回 </button>
  15. <button type="button" id="save-btn" class="ui secondary button">保存 </button>
  16. <button type="button" id="publish-btn" class="ui teal button">发布 </button>
  17. </div>
  18. </form>

注意:enctype的值为multipart/form-data

 

2 创建上传图片类——UploadImageUtils


  
  1. package com.hdq.blog_3.util;
  2. import org.springframework.web.multipart.MultipartFile;
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.util.UUID;
  6. public class UploadImageUtils {
  7. // 文件上传
  8. public static String upload(MultipartFile file){
  9. if(file.isEmpty()){
  10. return "";
  11. }
  12. String fileName = file.getOriginalFilename(); //获取文件名
  13. String suffixName = fileName.substring(fileName.lastIndexOf( ".")); //获取文件后缀名
  14. //重命名文件
  15. fileName = UUID.randomUUID().toString().replaceAll( "-", "") + suffixName;
  16. // windows下
  17. // String filePath="E:/picture/";
  18. //centos下
  19. String filePath= "/opt/findBugWeb/picture/";
  20. File dest = new File(filePath+fileName);
  21. if(!dest.getParentFile().exists()){
  22. dest.getParentFile().mkdirs();
  23. }
  24. try{
  25. file.transferTo(dest);
  26. } catch (IOException e){
  27. e.printStackTrace();
  28. }
  29. return filePath.substring(filePath.indexOf( "/"))+fileName;
  30. }
  31. }

 

3 配置图片访问路径的类——SourceMapperConfig

      该类可以指定图片的访问路径。


  
  1. package com.hdq.blog_3.sourceMapper;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
  5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
  6. //配置文件访问路径
  7. @Configuration
  8. public class SourceMapperConfig implements WebMvcConfigurer {
  9. // private String fileSavePath = "E:/picture/";
  10. String fileSavePath= "/opt/findBugWeb/picture/";
  11. /**
  12. * 配置资源映射
  13. * 意思是:如果访问的资源路径是以“/images/”开头的,
  14. * 就给我映射到本机的“E:/images/”这个文件夹内,去找你要的资源
  15. * 注意:E:/images/ 后面的 “/”一定要带上
  16. */
  17. @Override
  18. public void addResourceHandlers(ResourceHandlerRegistry registry) {
  19. registry.addResourceHandler( "/opt/findBugWeb/picture/**").addResourceLocations( "file:"+fileSavePath);
  20. }
  21. }

 

4 创建Controller类——BlogController


  
  1. package com.hdq.blog_3.web.admin;
  2. import com.hdq.blog_3.po.Blog;
  3. import com.hdq.blog_3.po.User;
  4. import com.hdq.blog_3.service.BlogService;
  5. import com.hdq.blog_3.service.TagService;
  6. import com.hdq.blog_3.service.TypeService;
  7. import com.hdq.blog_3.util.UploadImageUtils;
  8. import com.hdq.blog_3.vo.BlogQuery;
  9. import org.springframework.beans.factory.annotation.Autowired;
  10. import org.springframework.data.domain.Pageable;
  11. import org.springframework.data.domain.Sort;
  12. import org.springframework.data.web.PageableDefault;
  13. import org.springframework.stereotype.Controller;
  14. import org.springframework.ui.Model;
  15. import org.springframework.web.bind.annotation.*;
  16. import org.springframework.web.multipart.MultipartFile;
  17. import org.springframework.web.servlet.mvc.support.RedirectAttributes;
  18. import javax.servlet.http.HttpSession;
  19. @Controller
  20. @RequestMapping("/admin")
  21. public class BlogController {
  22. private static final String INPUT= "admin/blogs-input";
  23. private static final String LIST= "admin/blogs";
  24. private static final String REDIRECT_LIST= "redirect:/admin/blogs";
  25. @Autowired
  26. private BlogService blogService;
  27. @Autowired
  28. private TypeService typeService;
  29. @Autowired
  30. private TagService tagService;
  31. private void setTypeAndTag(Model model){
  32. model.addAttribute( "types",typeService.listType());
  33. model.addAttribute( "tags",tagService.listTag());
  34. }
  35. //新增 or 修改
  36. @PostMapping("/blogs")
  37. public String post(@RequestParam("picture") MultipartFile picture, Blog blog, RedirectAttributes attributes, HttpSession session){
  38. blog.setUser((User) session.getAttribute( "user"));
  39. blog.setType(typeService.getType(blog.getType().getId()));
  40. blog.setTags(tagService.listTag(blog.getTagIds()));
  41. //1.修改:picture为空,则不改变FirstPicture,否则改变FirstPicture。
  42. //2.新增:直接添加图片文件
  43. Blog b;
  44. if(blog.getId() == null){
  45. blog.setFirstPicture(UploadImageUtils.upload(picture)); //重点
  46. b=blogService.saveBlog(blog);
  47. } else{
  48. // isEmpty()与null的区别:前者表示内容是否为空,后者表示对象是否实例化,在这里前端发送请求到后端时,就实例化了picture对象
  49. if(picture.isEmpty()){
  50. blog.setFirstPicture(blogService.getBlog(blog.getId()).getFirstPicture()); //重点
  51. } else {
  52. blog.setFirstPicture(UploadImageUtils.upload(picture)); //重点
  53. }
  54. b=blogService.updateBlog(blog.getId(),blog);
  55. }
  56. if(b == null){
  57. attributes.addFlashAttribute( "message", "操作失败!");
  58. } else{
  59. attributes.addFlashAttribute( "message", "操作成功!");
  60. }
  61. return REDIRECT_LIST;
  62. }
  63. }

注意:以上部分不重要的代码已删掉,只留下重要部分。

 

三 运行结果展示

1 初始页面

 

2 新增成功页面

a.添加图片

b.新增成功

 

3 修改成功页面

 

至此就完成了,都看到这了,点个赞吧!

 


转载:https://blog.csdn.net/qq_36134376/article/details/116107651
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场