文件上传(不生成临时文件)

  • 背景

    1. 有两个服务,A服务有一个文件上传的接口,B服务通过restTemplate调用A服务的接口上传一个文件。
    2. B服务已经拿到文件内容。那么是否能够在不需要生成临时文件的情况下上传文件到A服务呢?
  • 实现过程

    1. 定义内容

      String fileStr = "文件内容";
    2. 字符串转换成byte[]

          byte[] xmlBytes = fileStr.getBytes();
    3. 自定义MultipartFile实现类

      public class BASE64DecodedMultipartFile implements MultipartFile {
          // 上传文件字节流
          private final byte[] imgContent;
          // 上传文件的文件名
          private final String originalFilename;
      
          public BASE64DecodedMultipartFile(byte[] imgContent, String originalFilename) {
              this.imgContent = imgContent;
              this.originalFilename = originalFilename;
          }
      
          @Override
          public String getName() {
              // TODO - implementation depends on your requirements
              return null;
          }
      
          @Override
          public String getOriginalFilename() {
              // TODO - implementation depends on your requirements
              return this.originalFilename;
          }
      
          @Override
          public String getContentType() {
              // TODO - implementation depends on your requirements
              return null;
          }
      
          @Override
          public boolean isEmpty() {
              return imgContent == null || imgContent.length == 0;
          }
      
          @Override
          public long getSize() {
              return imgContent.length;
          }
      
          @Override
          public byte[] getBytes() throws IOException {
              return imgContent;
          }
      
          @Override
          public InputStream getInputStream() throws IOException {
              return new ByteArrayInputStream(imgContent);
          }
      
          @Override
          public void transferTo(File dest) throws IOException, IllegalStateException {
              new FileOutputStream(dest).write(imgContent);
          }
      }
    4. 构造上传文件对象

      MultipartFile mf = new BASE64DecodedMultipartFile(xmlBytes, fileName);
    5. 通过restTemplate调用远程接口

      HttpHeaders headers = new HttpHeaders();
      headers.setContentType(MediaType.MULTIPART_FORM_DATA);
      MultiValueMap requestparams = new LinkedMultiValueMap<>();
      requestparams.add("file", mf.getResource());
      requestparams.add("filename", mf.getOriginalFilename());
      HttpEntity> requestEntity = new HttpEntity<>(requestparams, headers);
      RestTemplate restTemplate = new RestTemplate();
      Object resultVo = restTemplate.postForObject(url, requestEntity, Object.class);

你可能感兴趣的:(文件上传(不生成临时文件))