Postman 上传 multipartfile

Postman 上传 multipartfile

1.需求描述

通过postman上传一张png图片(其他文件也可),服务端保存到指定目录

简单定义前端入参

​ 文件使用 file 字段存储

​ 文件别称 name 存储

2.Postman端

Postman 上传 multipartfile_第1张图片

  1. 切换到body
  2. 选择form-data
  3. 修改file类型为file
  4. 选择待上传文件

3.后端代码

  1. 后端model使用MultipartFile

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    class BaseFile implements Serializable {
        private String name;
        private MultipartFile file;
    }
    
  2. 后端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();
    }
    

你可能感兴趣的:(java,java,upload)