[关闭]
@File 2020-04-30T06:44:42.000000Z 字数 1245 阅读 55

spring-boot 文件上传

java


multipart/form-data

web实现

  1. <form action="http://localhost:8086/lidaye/uploadFile" method="post" enctype="multipart/form-data">
  2. <input type="file" name="imgs">
  3. <input type="file" name="imgs">
  4. <input type="submit">
  5. </form>

java实现

MultipartFile 对象

  • getName() 参数名,对应 input:name
  • getSize() 文件大小
  • getContentType() 文件类型
  • getOriginalFilename() 文件名包括后缀
  • getResource() 取资源对象 Resource(包含InputStream)
  • getInputStream() 取输入流对象 InputStream(Bytes)
  • getBytes() 取字节数组
  • isEmpty() 是否空文件

方法一:常规流读取

  1. @RestController
  2. @RequestMapping("/lidaye")
  3. public class TestComtroller {
  4. @PostMapping("/uploadFile")
  5. public Object uploadFile(@RequestParam List<MultipartFile> imgs) {
  6. imgs.forEach(m -> {
  7. // 拿到流
  8. try(InputStream inputStream = m.getInputStream()) {
  9. // 装文件内容
  10. StringBuilder sb = new StringBuilder();
  11. // 一次读取1024B
  12. byte[] b = new byte[1024];
  13. // 读
  14. while (inputStream.read(b) > 0) {
  15. sb.append(new String(b, Charset.defaultCharset()));
  16. }
  17. // 当前文件的内容
  18. System.out.println(sb);
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. });
  23. return true;
  24. }
  25. }

方法二:直接拿字节

  1. @RestController
  2. @RequestMapping("/lidaye")
  3. public class TestComtroller {
  4. @PostMapping("/uploadFile")
  5. public Object uploadFile(@RequestParam List<MultipartFile> imgs) {
  6. imgs.forEach(m -> {
  7. try {
  8. // 直接获取到完整的内容
  9. System.out.println(new String(m.getBytes(),Charset.defaultCharset()));
  10. } catch (IOException e) {
  11. e.printStackTrace();
  12. }
  13. });
  14. return true;
  15. }
  16. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注