關(guān)于Springboot在新增和修改下上傳圖片并顯示的問題
解決的問題:
本篇文章除了解決上傳圖片并顯示的問題,還有就是在新增和修改下的圖片上傳如何處理。在這里新增和修改的頁面是同一頁面,修改的時(shí)候,將會把值帶過去,但是由于類型為file的input標(biāo)簽是不能給其賦值的,那么若不改變原來圖片,但是input標(biāo)簽中又沒有值,這時(shí)怎么處理呢?
一 運(yùn)行環(huán)境
開發(fā)工具:IDEA
后端:Springboot+JPA
前端:thymeleaf+semantic UI
二 代碼實(shí)現(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)容省略,以下為重點(diǎn)-->
<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)容省略,以上為重點(diǎn)-->
<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/”開頭的,
* 就給我映射到本機(jī)的“E:/images/”這個(gè)文件夾內(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));//重點(diǎn)
b=blogService.saveBlog(blog);
}else{
// isEmpty()與null的區(qū)別:前者表示內(nèi)容是否為空,后者表示對象是否實(shí)例化,在這里前端發(fā)送請求到后端時(shí),就實(shí)例化了picture對象
if(picture.isEmpty()){
blog.setFirstPicture(blogService.getBlog(blog.getId()).getFirstPicture());//重點(diǎn)
}else {
blog.setFirstPicture(UploadImageUtils.upload(picture));//重點(diǎn)
}
b=blogService.updateBlog(blog.getId(),blog);
}
if(b == null){
attributes.addFlashAttribute("message","操作失敗!");
}else{
attributes.addFlashAttribute("message","操作成功!");
}
return REDIRECT_LIST;
}
}
注意:以上部分不重要的代碼已刪掉,只留下重要部分。
三 運(yùn)行結(jié)果展示
1 初始頁面

2 新增成功頁面
a.添加圖片

b.新增成功

3 修改成功頁面

到此這篇關(guān)于關(guān)于Springboot在新增和修改下上傳圖片并顯示的問題的文章就介紹到這了,更多相關(guān)springboot新增修改上傳圖片內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java 文件傳輸助手的實(shí)現(xiàn)(單機(jī)版)
這篇文章主要介紹了Java 文件傳輸助手的實(shí)現(xiàn)(單機(jī)版),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
java調(diào)用微信現(xiàn)金紅包接口的心得與體會總結(jié)
這篇文章主要介紹了java調(diào)用微信現(xiàn)金紅包接口的心得與體會總結(jié),有需要的朋友可以了解一下。2016-11-11
MyEclipse開發(fā)一個(gè)webservice接口
這篇文章主要為大家詳細(xì)介紹了MyEclipse開發(fā)一個(gè)webservice接口,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
Java中super關(guān)鍵字介紹以及super()的使用
這幾天看到類在繼承時(shí)會用到this和super,這里就做了一點(diǎn)總結(jié),下面這篇文章主要給大家介紹了關(guān)于Java中super關(guān)鍵字介紹以及super()使用的相關(guān)資料,需要的朋友可以參考下2022-01-01

