spring boot 圖片上傳與顯示功能實(shí)例詳解
首先描述一下問(wèn)題,spring boot 使用的是內(nèi)嵌的tomcat, 所以不清楚文件上傳到哪里去了, 而且spring boot 把靜態(tài)的文件全部在啟動(dòng)的時(shí)候都會(huì)加載到classpath的目錄下的,所以上傳的文件不知相對(duì)于應(yīng)用目錄在哪,也不知怎么寫訪問(wèn)路徑合適,對(duì)于新手的自己真的一頭霧水。
后面想起了官方的例子,沒(méi)想到一開始被自己找到的官方例子,后面太依賴百度谷歌了,結(jié)果發(fā)現(xiàn)只有官方的例子能幫上忙,而且?guī)蜕洗竺?,直接上密碼的代碼
package hello;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class FileUploadController {
private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);
public static final String ROOT = "upload-dir";
private final ResourceLoader resourceLoader;
@Autowired
public FileUploadController(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@RequestMapping(method = RequestMethod.GET, value = "/")
public String provideUploadInfo(Model model) throws IOException {
model.addAttribute("files", Files.walk(Paths.get(ROOT))
.filter(path -> !path.equals(Paths.get(ROOT)))
.map(path -> Paths.get(ROOT).relativize(path))
.map(path -> linkTo(methodOn(FileUploadController.class).getFile(path.toString())).withRel(path.toString()))
.collect(Collectors.toList()));
return "uploadForm";
}
//顯示圖片的方法關(guān)鍵 匹配路徑像 localhost:8080/b7c76eb3-5a67-4d41-ae5c-1642af3f8746.png
@RequestMapping(method = RequestMethod.GET, value = "/{filename:.+}")
@ResponseBody
public ResponseEntity<?> getFile(@PathVariable String filename) {
try {
return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()));
} catch (Exception e) {
return ResponseEntity.notFound().build();
}
}
<strong>//上傳的方法</strong>
@RequestMapping(method = RequestMethod.POST, value = "/")
public String handleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes, HttpServletRequest request) {
System.out.println(request.getParameter("member"));
if (!file.isEmpty()) {
try {
Files.copy(file.getInputStream(), Paths.get(ROOT, file.getOriginalFilename()));
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
} catch (IOException|RuntimeException e) {
redirectAttributes.addFlashAttribute("message", "Failued to upload " + file.getOriginalFilename() + " => " + e.getMessage());
}
} else {
redirectAttributes.addFlashAttribute("message", "Failed to upload " + file.getOriginalFilename() + " because it was empty");
}
return "redirect:/";
}
}
看完上面的代碼可以理解到spring boot 的存取文件思路了,存的時(shí)候的路徑為
Paths.get(ROOT, filename).toString()))
這個(gè)路徑會(huì)在本地的工程根目錄上創(chuàng)建,不應(yīng)用部署里的目錄,所以一般的訪問(wèn)http訪問(wèn)不可能 ,所以它提供了ResourceLoader,利于這個(gè)類可以加載非應(yīng)用目錄的里文件然后返回
所以就可以讀取文件,所以就要寫getFIle方法來(lái)顯示圖片

如果大家對(duì)spring boot不是很了解,大家可以參考下面兩篇文章。
以上所述是小編給大家介紹的spring boot 圖片上傳與顯示功能實(shí)例詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
- Spring Boot實(shí)現(xiàn)圖片上傳功能
- spring boot實(shí)現(xiàn)上傳圖片并在頁(yè)面上顯示及遇到的問(wèn)題小結(jié)
- SpringBoot限制文件或圖片上傳大小的兩種配置方法
- spring boot實(shí)現(xiàn)圖片上傳和下載功能
- spring boot thymeleaf 圖片上傳web項(xiàng)目根目錄操作步驟
- 基于SpringBoot實(shí)現(xiàn)圖片上傳與顯示
- bootstrap fileinput組件整合Springmvc上傳圖片到本地磁盤
- Spring boot的上傳圖片功能實(shí)例詳解
- Spring Boot實(shí)現(xiàn)圖片上傳/加水印一把梭操作實(shí)例代碼
相關(guān)文章
springmvc+ajax+formdata上傳圖片代碼實(shí)例
這篇文章主要介紹了springmvc+ajax+formdata上傳圖片代碼實(shí)例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
解決Android Studio安裝后運(yùn)行出錯(cuò)dose not...和Internal error...
這篇文章主要介紹了解決Android Studio安裝后運(yùn)行出錯(cuò)dose not...和Internal error...的相關(guān)資料,需要的朋友可以參考下2017-03-03
常用數(shù)字簽名算法RSA與DSA的Java程序內(nèi)實(shí)現(xiàn)示例
這篇文章主要介紹了常用數(shù)字簽名算法RSA與DSA的Java程序內(nèi)實(shí)現(xiàn)示例,一般來(lái)說(shuō)DSA算法用于簽名的效率會(huì)比RSA要快,需要的朋友可以參考下2016-04-04
Springboot集成MongoDB無(wú)認(rèn)證與開啟認(rèn)證的配置方式
本文主要介紹了Springboot集成MongoDB無(wú)認(rèn)證與開啟認(rèn)證的配置方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-03-03
Java中八種基本數(shù)據(jù)類型的默認(rèn)值
這篇文章主要介紹了Java中八種基本數(shù)據(jù)類型的默認(rèn)值 的相關(guān)資料,需要的朋友可以參考下2016-07-07

