我正在使用 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
请求。我该如何解决这个问题?
问题是
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
,而不是缺少值的键。