spring boot 圖片上傳與顯示功能實例詳解。本站提示廣大學習愛好者:(spring boot 圖片上傳與顯示功能實例詳解)文章只能為提供參考,不一定能成為您想要的結果。以下是spring boot 圖片上傳與顯示功能實例詳解正文
首先描述一下問題,spring boot 使用的是內嵌的tomcat, 所以不清楚文件上傳到哪裡去了, 而且spring boot 把靜態的文件全部在啟動的時候都會加載到classpath的目錄下的,所以上傳的文件不知相對於應用目錄在哪,也不知怎麼寫訪問路徑合適,對於新手的自己真的一頭霧水。
後面想起了官方的例子,沒想到一開始被自己找到的官方例子,後面太依賴百度谷歌了,結果發現只有官方的例子能幫上忙,而且幫上大忙,直接上密碼的代碼
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";
}
//顯示圖片的方法關鍵 匹配路徑像 localhost:8080/b7c76eb3-5a67-4d41-ae5c-1642af3f8746.png" />
如果大家對spring boot不是很了解,大家可以參考下面兩篇文章。
Spring Boot 快速入門教程
Spring Boot 快速入門指南
以上所述是小編給大家介紹的spring boot 圖片上傳與顯示功能實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對網站的支持!