使用springboot 圖片上傳和顯示
阿新 • • 發佈:2018-12-15
一、application.properties配置檔案
###檔案上傳 springboot版本2.0.4 #是否啟用檔案上傳功能 spring.servlet.multipart.enabled=true #指定檔案寫入磁碟後的閾值,預設為0 spring.servlet.multipart.file-size-threshold=0 #指定檔案的位置, 沒有指定時會自動建立一個臨時資料夾 spring.servlet.multipart.location=D:/springboot/upload #指定上傳檔案大小, 預設1M spring.servlet.multipart.max-file-size=50Mb #指定multipart / form-data請求允許的最大大小, 預設10M spring.servlet.multipart.max-request-size=100Mb #是否在檔案或引數訪問時懶惰地解析多部分請求 spring.servlet.multipart.resolve-lazily=false #圖片上傳路徑對映 自定義屬性 upload.picture.path=D:/springboot/upload/
二、控制層
@Controller public class PhotoController extends BaseController { @Value("${upload.picture.path}") private String uploadPicturePath; @javax.annotation.Resource private ResourceLoader resourceLoader; /** * @Description //上傳 * @Param [multipartFile] * @Author oneTi * @Date 15:10 2018/8/17 * @Return java.lang.String **/ @RequestMapping("/photo/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile multipartFile){ try{ //multipartFile.getOriginalFilename() 獲取檔案原始名稱 //new File(multipartFile.getOriginalFilename()) 根據獲取到的原始檔名建立目標檔案 //multipartFile.transferTo() 將收到的檔案傳輸到目標檔案中 multipartFile.transferTo(new File(multipartFile.getOriginalFilename())); } catch (IOException e){ e.printStackTrace(); } return "false"; } /** * @Description //顯示 * @Param [fileName] * @Author oneTi * @Date 15:11 2018/8/17 * @Return org.springframework.http.ResponseEntity<org.springframework.core.io.Resource> **/ @RequestMapping("/{fileName:.+}") @ResponseBody public ResponseEntity<Resource> show(@PathVariable String fileName){ try { //resourceLoader.getResource("file:" + uploadPicturePath + fileName) 返回指定路徑的資源控制代碼,這裡返回的就是URL [file:D:/springboot/upload/test.png] //ResponseEntity.ok(T) 返回指定內容主體 return ResponseEntity.ok(resourceLoader.getResource("file:" + uploadPicturePath + fileName)); } catch (Exception e) { return ResponseEntity.notFound().build(); } } }
三、前端頁面
<!--圖片上傳表單-->
<form action="/photo/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="">
<input type="submit" value="submit">
</form>
<!--圖片顯示-->
<img src="/test.png" alt="">
就用簡單的img標籤測試一下。
以上就是圖片上傳以及瀏覽器上顯示的過程~