I am using Springboot to return a MultipartFile as my response for an endpoint.
MultipartFile file = new MockMultipartFile(
imageUploadResponse.getKey(),
imageUploadResponse.getKey(),
imageUploadResponse.getMimeType(),
imageUploadResponse.getInputStream()
);
return new ResponseEntity<>(file, headers, HttpStatus.OK);
However, the JSON returned to the client looks like this:
{ ..., "inputStream" }
Which is invalid JSON and breaks my $.ajax request. How do I fix this issue?
The issue was MockMultipartFile has a getter that does not serialize properly.
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(this.content);
}
I solved it by extending 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;
}
}
Now inputStream is null in the JSON response, instead of a key with a missing value.