Reputation: 199
I want to get the byte content of the File. Here is my controller:
@PostMapping("/files")
@ResponseStatus(HttpStatus.OK)
public List<UserFilesResponse> uploadFile(@RequestPart("file") FilePart file) {
// I want to get the bytes[] content of my file. How can I do it please ??
}
Upvotes: 3
Views: 4399
Reputation: 294
@ResponseStatus(HttpStatus.OK)
public List<UserFilesResponse> uploadFile(@RequestPart("file") MultipartFile file) {
byte[] fileBytes = file.getBytes();
//rest of code
}
I would suggest to use multipart file instead of just file part, this will enable you to call the getBytes() method and get the byte array.
Upvotes: 0
Reputation: 19
Convert filepart to Byte Array
private byte[] convertFilePartToByteArray(FilePart file) throws IOException {
File convFile = new File(file.filename());
file.transferTo(convFile);
return Files.readAllBytes(convFile.toPath());
}
Upvotes: 0
Reputation: 131
As M. Deinum mentioned, you should use content
I would also recommend https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/io/buffer/DataBufferUtils.html#join-org.reactivestreams.Publisher-
DataBufferUtils.join(filePart.content())
.map(dataBuffer -> dataBuffer.asByteBuffer().array())
Upvotes: 4