How to read a Multipart file as a string in Spring?

I want to publish a text file from my desktop using the Advanced Rest Client. This is my controller:

@RequestMapping(value = "/vsp/debug/compareConfig/{deviceIp:.*}", method = RequestMethod.POST, consumes = { "multipart/form-data" }, produces = { "application/json" })

public ResponseEntity<SuccessResult> compareCLIs(HttpServletRequest request, @RequestParam("file") MultipartFile file, @PathVariable("deviceIp") String device) 
{
log.info(file.getOriginalFilename());
byte[] bytearr = file.getBytes();
log.info("byte length: ", bytearr.length);
log.info("Size : ", file.getSize());

}

This does not return a value for byte length or file size. I want to read the values ​​of a file in a StringBuffer. Can anyone point out pointers to this? I'm not sure if I need to save this file before parsing it in a line. If so, how to save the file in the workspace?

+4
source share
2 answers

If you want to load the contents of the Multipart file into String, the easiest solution:

String content = new String(file.getBytes());

Or, if you want to specify an encoding:

String content = new String(file.getBytes(), "UTF-8");

However, if your file is huge, this solution may not be the best.

+5
source

-, Spring, , -, .

String, Apache Commons IOUtils,

ByteArrayInputStream stream = new   ByteArrayInputStream(file.getBytes());
String myString = IOUtils.toString(stream, "UTF-8");
+2

All Articles