spring boot 圖片的上傳與顯示


http://blog.csdn.net/a625013/article/details/52414470

 

首先描述一下問題,spring boot 使用的是內嵌的tomcat, 所以不清楚文件上傳到哪里去了, 而且spring boot 把靜態的文件全部在啟動的時候都會加載到classpath的目錄下的,所以上傳的文件不知相對於應用目錄在哪,也不知怎么寫訪問路徑合適,對於新手的自己真的一頭霧水。

 

后面想起了官方的例子,沒想到一開始被自己找到的官方例子,后面太依賴百度谷歌了,結果發現只有官方的例子能幫上忙,而且幫上大忙,直接上密碼的代碼

 

[java]  view plain  copy
 
  1. package hello;  
  2.   
  3. import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;  
  4. import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;  
  5.   
  6. import java.io.IOException;  
  7. import java.nio.file.Files;  
  8. import java.nio.file.Paths;  
  9. import java.util.stream.Collectors;  
  10.   
  11. import javax.servlet.http.HttpServletRequest;  
  12.   
  13. import org.slf4j.Logger;  
  14. import org.slf4j.LoggerFactory;  
  15. import org.springframework.beans.factory.annotation.Autowired;  
  16. import org.springframework.core.io.ResourceLoader;  
  17. import org.springframework.http.ResponseEntity;  
  18. import org.springframework.stereotype.Controller;  
  19. import org.springframework.ui.Model;  
  20. import org.springframework.web.bind.annotation.PathVariable;  
  21. import org.springframework.web.bind.annotation.RequestMapping;  
  22. import org.springframework.web.bind.annotation.RequestMethod;  
  23. import org.springframework.web.bind.annotation.RequestParam;  
  24. import org.springframework.web.bind.annotation.ResponseBody;  
  25. import org.springframework.web.multipart.MultipartFile;  
  26. import org.springframework.web.servlet.mvc.support.RedirectAttributes;  
  27.   
  28. @Controller  
  29. public class FileUploadController {  
  30.   
  31.     private static final Logger log = LoggerFactory.getLogger(FileUploadController.class);  
  32.   
  33.     public static final String ROOT = "upload-dir";  
  34.   
  35.     private final ResourceLoader resourceLoader;  
  36.   
  37.     @Autowired  
  38.     public FileUploadController(ResourceLoader resourceLoader) {  
  39.         this.resourceLoader = resourceLoader;  
  40.     }  
  41.   
  42.     @RequestMapping(method = RequestMethod.GET, value = "/")  
  43.     public String provideUploadInfo(Model model) throws IOException {  
  44.   
  45.         model.addAttribute("files", Files.walk(Paths.get(ROOT))  
  46.                 .filter(path -> !path.equals(Paths.get(ROOT)))  
  47.                 .map(path -> Paths.get(ROOT).relativize(path))  
  48.                 .map(path -> linkTo(methodOn(FileUploadController.class).getFile(path.toString())).withRel(path.toString()))  
  49.                 .collect(Collectors.toList()));  
  50.   
  51.         return "uploadForm";  
  52.     }  
[java]  view plain  copy
 
  1. //顯示圖片的方法關鍵 匹配路徑像 localhost:8080/b7c76eb3-5a67-4d41-ae5c-1642af3f8746.png  
  2.     @RequestMapping(method = RequestMethod.GET, value = "/{filename:.+}")  
  3.     @ResponseBody  
  4.     public ResponseEntity<?> getFile(@PathVariable String filename) {  
  5.   
  6.         try {  
  7.             return ResponseEntity.ok(resourceLoader.getResource("file:" + Paths.get(ROOT, filename).toString()));  
  8.         } catch (Exception e) {  
  9.             return ResponseEntity.notFound().build();  
  10.         }  
  11.     }  
[java]  view plain  copy
 
  1. <strong>//上傳的方法</strong>  
  2.     @RequestMapping(method = RequestMethod.POST, value = "/")  
  3.     public String handleFileUpload(@RequestParam("file") MultipartFile file,  
  4.                                    RedirectAttributes redirectAttributes, HttpServletRequest request) {  
  5.         System.out.println(request.getParameter("member"));  
  6.         if (!file.isEmpty()) {  
  7.             try {  
  8.                 Files.copy(file.getInputStream(), Paths.get(ROOT, file.getOriginalFilename()));  
  9.                 redirectAttributes.addFlashAttribute("message",  
  10.                         "You successfully uploaded " + file.getOriginalFilename() + "!");  
  11.             } catch (IOException|RuntimeException e) {  
  12.                 redirectAttributes.addFlashAttribute("message", "Failued to upload " + file.getOriginalFilename() + " => " + e.getMessage());  
  13.             }  
  14.         } else {  
  15.             redirectAttributes.addFlashAttribute("message", "Failed to upload " + file.getOriginalFilename() + " because it was empty");  
  16.         }  
  17.   
  18.         return "redirect:/";  
  19.     }  
  20.   
  21. }  

 

看完上面的代碼可以理解到spring boot 的存取文件思路了,存的時候的路徑為

[java]  view plain  copy
 
  1. Paths.get(ROOT, filename).toString()))  
[java]  view plain  copy
 
  1. 這個路徑會在本地的工程根目錄上創建,不應用部署里的目錄,所以一般的訪問http訪問不可能 ,所以它提供了ResourceLoader,利於這個類可以加載非應用目錄的里文件然后返回  
[java]  view plain  copy
 
  1. 所以就可以讀取文件,所以就要寫getFIle方法來顯示圖片  
 
3


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM