Skip to content

Commit

Permalink
contentLength support for Resource decoding
Browse files Browse the repository at this point in the history
Expose the known content length, if known, in the InputStreamResource returned by ResourceHttpMessageConverter or
ResourceDecoder.

See gh-24292
  • Loading branch information
ofaizulin authored and rstoyanchev committed Jan 8, 2020
1 parent e3e7d90 commit e96b71a
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 0 deletions.
Expand Up @@ -83,6 +83,11 @@ public Resource decode(DataBuffer dataBuffer, ResolvableType elementType,
public String getFilename() {
return filename;
}

@Override
public long contentLength() {
return bytes.length;
}
};
}
else if (Resource.class.isAssignableFrom(clazz)) {
Expand Down
Expand Up @@ -105,4 +105,22 @@ public void decodeToMono() {
Collections.singletonMap(ResourceDecoder.FILENAME_HINT, "testFile"));
}

@Test
public void decodeInputStreamResource() {
Flux<DataBuffer> input = Flux.concat(dataBuffer(this.fooBytes), dataBuffer(this.barBytes));
testDecodeAll(input, InputStreamResource.class, step -> step
.consumeNextWith(resource -> {
try {
byte[] bytes = StreamUtils.copyToByteArray(resource.getInputStream());
assertThat(new String(bytes)).isEqualTo("foobar");
assertThat(resource.contentLength()).isEqualTo(fooBytes.length + barBytes.length);
}
catch (IOException ex) {
throw new AssertionError(ex.getMessage(), ex);
}
})
.expectComplete()
.verify());
}

}
Expand Up @@ -84,6 +84,11 @@ protected Resource readInternal(Class<? extends Resource> clazz, HttpInputMessag
public String getFilename() {
return inputMessage.getHeaders().getContentDisposition().getFilename();
}

@Override
public long contentLength() {
return inputMessage.getHeaders().getContentLength();
}
};
}
else if (Resource.class == clazz || ByteArrayResource.class.isAssignableFrom(clazz)) {
Expand Down
Expand Up @@ -80,10 +80,12 @@ public void shouldReadInputStreamResource() throws IOException {
inputMessage.getHeaders().setContentType(MediaType.IMAGE_JPEG);
inputMessage.getHeaders().setContentDisposition(
ContentDisposition.builder("attachment").filename("yourlogo.jpg").build());
inputMessage.getHeaders().setContentLength(123);
Resource actualResource = converter.read(InputStreamResource.class, inputMessage);
assertThat(actualResource).isInstanceOf(InputStreamResource.class);
assertThat(actualResource.getInputStream()).isEqualTo(body);
assertThat(actualResource.getFilename()).isEqualTo("yourlogo.jpg");
assertThat(actualResource.contentLength()).isEqualTo(123);
}
}

Expand Down

0 comments on commit e96b71a

Please sign in to comment.