https://blog.csdn.net/a625013/article/details/52414470
build.gradle
buildscript { repositories { mavenCentral() } dependencies { classpath('org.springframework.boot:spring-boot-gradle-plugin:1.5.9.RELEASE') } } group "com.li" version "1.0-SNAPSHOT" apply plugin: "java" //java 插件 apply plugin: "org.springframework.boot" //spring boot 插件 apply plugin: "io.spring.dependency-management" apply plugin: "application" //应用 //mainClassName = "Main.Application" sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile("org.springframework.boot:spring-boot-starter-web", "org.springframework.boot:spring-boot-starter-activemq", "org.springframework.boot:spring-boot-starter-test", "org.springframework.boot:spring-boot-starter-cache", "org.springframework.boot:spring-boot-devtools") runtime ("org.apache.tomcat.embed:tomcat-embed-jasper") testCompile group: 'junit', name: 'junit', version: '4.12' }
1:spring boot提供了读取服务器路径之外图片,文件的方法。
1.1 :上传方法
//上传的方法 @RequestMapping(method = RequestMethod.POST, value = "/upload") 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:/"; }
1.2:
package com.li.controller; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; 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.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.util.UUID; import java.util.stream.Collectors; @Controller public class FileUploadController { // private static final Logger log = LoggerFactory.getLogger(FileUploadController.class); public static final String ROOT = "d://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 @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(); } } //上传的方法 @RequestMapping(method = RequestMethod.POST, value = "/upload") 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:/"; } // @RequestMapping("/save") // public String save(@RequestParam(value = "file") MultipartFile file, userInfo uf, RedirectAttributes attributes, HttpServletRequest request) { // if (uf != null) { // if (!file.isEmpty()) { // String fileName = UUID.randomUUID().toString().replaceAll("-", "") + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); // String filePath ="/Users/thomas-wu/upload/" + fileName; // System.out.println(filePath); // try { // file.transferTo(new File(filePath)); // } catch (IOException e) { // e.printStackTrace(); // } // uf.setHead_href("getimgs?address="+filePath); // } // // } // String result = userService.saveUser(uf); // JSONObject jb = JSONObject.fromObject(result); // if (jb.getInt("status") == 1 && "信息保存成功".equals(jb.getString("msg"))) { // attributes.addFlashAttribute("error", "信息保存成功"); // return "redirect:/user"; // } // attributes.addFlashAttribute("error", "信息保存失败"); // return "redirect:/edit"; // } @RequestMapping("/getimgs") public void getimg(String address, HttpServletRequest request, HttpServletResponse response) throws IOException{ try { FileInputStream hFile=new FileInputStream(address); int i=hFile.available(); byte data[]=new byte[i]; hFile.read(data); hFile.close(); response.setContentType("image/*"); OutputStream toClient=response.getOutputStream(); toClient.write(data); toClient.close(); }catch (IOException e){ PrintWriter toClient=response.getWriter(); response.setContentType("text/html;charset=gb2312"); toClient.write("无法打开图片"); toClient.close(); } } }