Springboot MultipartFile 响应包含无效的 json“inputStream”,没有值

问题描述 投票:0回答:1

我正在使用 Springboot 返回

MultipartFile
作为我对端点的响应。

        MultipartFile file = new MockMultipartFile(
            imageUploadResponse.getKey(), 
            imageUploadResponse.getKey(), 
            imageUploadResponse.getMimeType(), 
            imageUploadResponse.getInputStream()
        );
        return new ResponseEntity<>(file, headers, HttpStatus.OK);

但是,返回给客户端的 JSON 是这样的:

{ ..., "inputStream" }

这是无效的 JSON,并且破坏了我的

$.ajax
请求。我该如何解决这个问题?

spring-boot multipartfile
1个回答
0
投票

问题是

MockMultipartFile
有一个无法正确序列化的 getter。


    @Override
    public InputStream getInputStream() throws IOException {
        return new ByteArrayInputStream(this.content);
    }

我通过扩展解决了这个问题

MockMultipartFile

public class MultipartFileResponse extends MockMultipartFile {

  public MultipartFileResponse(String name, String originalFilename, String contentType, InputStream contentStream)
      throws IOException {
    super(name, originalFilename, contentType, contentStream);
  }

  // Parent class getInputStream is not serializable and
  // we don't need it, so we override and return null.
  @Override 
  public InputStream getInputStream() throws IOException {
    return null;
  }
  
}

现在,JSON 响应中的

inputStream
null
,而不是缺少值的键。

© www.soinside.com 2019 - 2024. All rights reserved.