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
posted @ 2017-09-21 08:57  白煤球  阅读(6059)  评论(0编辑  收藏  举报