3

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 ?? } 
3
  • You can use content for that? However what do you want to do with the byte[]? If to store it somewhere use one of the transferTo methods. Commented Jun 21, 2021 at 12:11
  • Thanks for the note. I want the byte[] because I save to Google Cloud Storage and I do it this way: storage.create(blobInfo, <byte[]>); So I can get the blobinfo, I need to have the byte[] to store the Data to GCloud Storage. Thanks Commented Jun 21, 2021 at 13:48
  • 2
    You should use the content then and read the DataBuffer. Commented Jun 22, 2021 at 5:54

3 Answers 3

4

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()) 
Sign up to request clarification or add additional context in comments.

2 Comments

Is it a good idea to convert it to a byte array and then storing it in the database?
well, the question was about getting bytes from FilePart. The decision of storing byte array in DB or FS or any cloud should depend on your business-process. It's a topic for a separate question :)
0

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()); } 

Comments

0
@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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.