springboot 文件上傳下載
阿新 • • 發佈:2018-08-14
photos 字符 ddp 數據 use 示例 nbsp ear oid
關鍵點:
1,使用 POST 請求
2,consumes=MediaType.MULTIPART_FROM_DATA_VALUE
3,@RequestParm 裏面的字符串和前端 input 控件的 name 值一致
上傳文件示例:
@PostMapping(value="/photos", consumes=MediaType.MULTIPART_FROM_DATA_VALUE) public void addPhoto(@RequestParm("photo") MultipartFile imgFile) throws Exception{ // 保存文件 FileOutputStream fos = newFileOutputStream("target/", imgFile.getOriginalFilename()); IOUtils.copy(imgFile.getInputStream(), fos); fos.close(); }
帶返回值上傳文件示例(返回二進制數據,讓用戶看到上傳的圖片長什麽樣):
@PostMapping(value="/icon", consumes=MediaType.MULTIPART_FROM_DATA_VALUE) public Byte[] addIcon(@RequestParm("photo") MultipartFile imgFile) throwsException{ // 用戶上傳文件的二進制數據 InputStream is = imgFile.getInputStream(); // 保存文件 FileOutputStream fos = new FileOutputStream("target/", imgFile.getOriginalFilename()); IOUtils.copy(is, fos); fos.close(); // 返回文件 return IOUtils.toByteArray(is); }
下載文件示例:
@GetMapping(value="/{userId}/photos", consumes=MediaType.MULTIPART_FROM_DATA_VALUE)public void getPhoto(@RequestParm("photo") MultipartFile imgFile) throws Exception{ // 返回文件 String userPhotoImgSrc = "src/test/10001.jpg"; InputStream is = new FileInputStream(userPhotoImgSrc); return IOUtils.toByteArray(is); }
springboot 文件上傳下載