Junior — Middle
How can you configure working with binary values in Spring Framework?
sobes.tech AI
Answer from AI
In Spring Framework, working with binary data is often related to handling files, streams, or binary data in HTTP requests and responses. To configure and work with binary values, the following approaches can be used:
- Using
byte[]orInputStreamtypes in controllers — for receiving or returning binary data.
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
byte[] bytes = file.getBytes();
// processing binary data
return ResponseEntity.ok("File uploaded");
}
@GetMapping("/download")
public ResponseEntity<byte[]> downloadFile() {
byte[] data = ...; // obtaining binary data
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=file.bin")
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(data);
}
- Serialization/deserialization configuration — if JSON is used, binary data can be encoded in Base64, for example, using Jackson:
public class DataWrapper {
private byte[] data;
// getters and setters
}
Jackson will automatically encode byte[] in Base64.
-
Using
ResourceandInputStreamResourcefor transferring large binary files without loading them into memory. -
Configuring MultipartResolver for uploading files via forms.
Thus, the configuration depends on the specific task, but the key point is the correct choice of data types (byte[], InputStream, Resource) and proper configuration of HTTP headers for transmitting binary data.