简体   繁体   中英

Java Convert FilePart to byte[] in Springboot using Webflux

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 ??
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM