關(guān)于Springboot在新增和修改下上傳圖片并顯示的問題
解決的問題:
本篇文章除了解決上傳圖片并顯示的問題,還有就是在新增和修改下的圖片上傳如何處理。在這里新增和修改的頁面是同一頁面,修改的時候,將會把值帶過去,但是由于類型為file的input標簽是不能給其賦值的,那么若不改變原來圖片,但是input標簽中又沒有值,這時怎么處理呢?
一 運行環(huán)境
開發(fā)工具:IDEA
后端:Springboot+JPA
前端:thymeleaf+semantic UI
二 代碼實現(xiàn)
springboot中已經(jīng)內(nèi)嵌了上傳圖片的依賴包,因此不需要再添加額外依賴。
1 前端頁面
<form id="blog-form" action="#" th:object="${blog}" th:action="@{/admin/blogs}" method="post" enctype="multipart/form-data" class="ui form"> <!--該部分內(nèi)容省略,以下為重點--> <div class="required field"> <div class="ui left labeled input"> <label class="ui teal basic label">首圖</label> <img src="" th:src="@{*{firstPicture}}" alt="" style="width: 500px !important;"> <!-- 不能給input type="file"文件賦值--> <input type="file" name="picture"> <!--<input type="text" name="firstPicture" th:value="*{firstPicture}" placeholder="首圖引用地址">--> </div> </div> <!--該部分內(nèi)容省略,以上為重點--> <div class="ui right aligned container"> <button type="button" class="ui button" onclick="window.history.go(-1)">返回</button> <button type="button" id="save-btn" class="ui secondary button">保存</button> <button type="button" id="publish-btn" class="ui teal button">發(fā)布</button> </div> </form>
注意:enctype的值為multipart/form-data
2 創(chuàng)建上傳圖片類——UploadImageUtils
package com.hdq.blog_3.util; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.UUID; public class UploadImageUtils { // 文件上傳 public static String upload(MultipartFile file){ if(file.isEmpty()){ return ""; } String fileName = file.getOriginalFilename();//獲取文件名 String suffixName = fileName.substring(fileName.lastIndexOf("."));//獲取文件后綴名 //重命名文件 fileName = UUID.randomUUID().toString().replaceAll("-","") + suffixName; // windows下 // String filePath="E:/picture/"; //centos下 String filePath="/opt/findBugWeb/picture/"; File dest = new File(filePath+fileName); if(!dest.getParentFile().exists()){ dest.getParentFile().mkdirs(); } try{ file.transferTo(dest); }catch (IOException e){ e.printStackTrace(); } return filePath.substring(filePath.indexOf("/"))+fileName; } }
3 配置圖片訪問路徑的類——SourceMapperConfig
該類可以指定圖片的訪問路徑。
package com.hdq.blog_3.sourceMapper; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; //配置文件訪問路徑 @Configuration public class SourceMapperConfig implements WebMvcConfigurer { // private String fileSavePath = "E:/picture/"; String fileSavePath="/opt/findBugWeb/picture/"; /** * 配置資源映射 * 意思是:如果訪問的資源路徑是以“/images/”開頭的, * 就給我映射到本機的“E:/images/”這個文件夾內(nèi),去找你要的資源 * 注意:E:/images/ 后面的 “/”一定要帶上 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/opt/findBugWeb/picture/**").addResourceLocations("file:"+fileSavePath); } }
4 創(chuàng)建Controller類——BlogController
package com.hdq.blog_3.web.admin; import com.hdq.blog_3.po.Blog; import com.hdq.blog_3.po.User; import com.hdq.blog_3.service.BlogService; import com.hdq.blog_3.service.TagService; import com.hdq.blog_3.service.TypeService; import com.hdq.blog_3.util.UploadImageUtils; import com.hdq.blog_3.vo.BlogQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.web.PageableDefault; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpSession; @Controller @RequestMapping("/admin") public class BlogController { private static final String INPUT="admin/blogs-input"; private static final String LIST="admin/blogs"; private static final String REDIRECT_LIST="redirect:/admin/blogs"; @Autowired private BlogService blogService; @Autowired private TypeService typeService; @Autowired private TagService tagService; private void setTypeAndTag(Model model){ model.addAttribute("types",typeService.listType()); model.addAttribute("tags",tagService.listTag()); } //新增 or 修改 @PostMapping("/blogs") public String post(@RequestParam("picture") MultipartFile picture, Blog blog, RedirectAttributes attributes, HttpSession session){ blog.setUser((User) session.getAttribute("user")); blog.setType(typeService.getType(blog.getType().getId())); blog.setTags(tagService.listTag(blog.getTagIds())); //1.修改:picture為空,則不改變FirstPicture,否則改變FirstPicture。 //2.新增:直接添加圖片文件 Blog b; if(blog.getId() == null){ blog.setFirstPicture(UploadImageUtils.upload(picture));//重點 b=blogService.saveBlog(blog); }else{ // isEmpty()與null的區(qū)別:前者表示內(nèi)容是否為空,后者表示對象是否實例化,在這里前端發(fā)送請求到后端時,就實例化了picture對象 if(picture.isEmpty()){ blog.setFirstPicture(blogService.getBlog(blog.getId()).getFirstPicture());//重點 }else { blog.setFirstPicture(UploadImageUtils.upload(picture));//重點 } b=blogService.updateBlog(blog.getId(),blog); } if(b == null){ attributes.addFlashAttribute("message","操作失敗!"); }else{ attributes.addFlashAttribute("message","操作成功!"); } return REDIRECT_LIST; } }
注意:以上部分不重要的代碼已刪掉,只留下重要部分。
三 運行結(jié)果展示
1 初始頁面
2 新增成功頁面
a.添加圖片
b.新增成功
3 修改成功頁面
到此這篇關(guān)于關(guān)于Springboot在新增和修改下上傳圖片并顯示的問題的文章就介紹到這了,更多相關(guān)springboot新增修改上傳圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)
這篇文章主要介紹了詳解JAVAEE——SSH三大框架整合(spring+struts2+hibernate),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07idea配置檢查XML中SQL語法及書寫sql語句智能提示的方法
idea連接了數(shù)據(jù)庫,也可以執(zhí)行SQL查到數(shù)據(jù),但是無法識別sql語句中的表導致沒有提示,下面這篇文章主要給大家介紹了關(guān)于idea配置檢查XML中SQL語法及書寫sql語句智能提示的相關(guān)資料,需要的朋友可以參考下2023-03-03Java工廠模式優(yōu)雅地創(chuàng)建對象以及提高代碼復用率和靈活性
Java工廠模式是一種創(chuàng)建型設(shè)計模式,通過定義一個工廠類來封裝對象的創(chuàng)建過程,將對象的創(chuàng)建和使用分離,提高代碼的可維護性和可擴展性,同時可以實現(xiàn)更好的代碼復用和靈活性2023-05-05SpringBoot如何通過Feign調(diào)用傳遞Header中參數(shù)
這篇文章主要介紹了SpringBoot通過Feign調(diào)用傳遞Header中參數(shù),本文給大家分享兩種解決方案給大家詳細講解,需要的朋友可以參考下2023-04-04springboot2中使用@JsonFormat注解不生效的解決
這篇文章主要介紹了springboot2中使用@JsonFormat注解不生效的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02