1.需求描述
通過postman上傳一張png圖片(其他文件也可),服務端保存到指定目錄
簡單定義前端入參
文件使用 file 字段存儲
文件別稱 name 存儲
2.Postman端
- 切換到body
- 選擇form-data
- 修改file類型為file
- 選擇待上傳文件
3.后端代碼
-
后端model使用MultipartFile
@Data @AllArgsConstructor @NoArgsConstructor class BaseFile implements Serializable { private String name; private MultipartFile file; }
-
后端controller (為了代碼演示,這里直接在controller保存文件)
@PostMapping("/upload") public void uploadFile(BaseFile baseFile) throws IOException { MultipartFile file = baseFile.getFile(); String name = baseFile.getName(); String originalFilename = file.getOriginalFilename(); long size = file.getSize(); byte[] bytes = file.getBytes(); String contentType = file.getContentType(); Resource resource = file.getResource(); System.out.println(originalFilename); System.out.println(size); System.out.println(contentType); InputStream inputStream = file.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream(UploadConfig.path + originalFilename); byte[] buffer = new byte[1024]; int len; while (-1 != (len = inputStream.read(buffer))) { fileOutputStream.write(buffer, 0, len); } fileOutputStream.flush(); fileOutputStream.close(); }