Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I want to post a text file from my desktop using 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 any value for byte length or file size. I want to read the file values to a StringBuffer. Can someone provide pointers regarding this? I am not sure if I need to save this file before parsing it to a string. If so how do I save the file in the workspace?

like image 797
nivedita rahurkar Avatar asked Jul 13 '15 21:07

nivedita rahurkar


People also ask

How do you convert a multipart to a string?

If you want to load the content of a Multipart file into a String, the easiest solution is: String content = new String(file.

How do I convert a multipart file to spring boot?

Using the transferTo() method, we simply have to create the File that we want to write the bytes to, then pass that file to the transferTo() method. The transferTo() method is useful when the MultipartFile only needs to be written to a File.


2 Answers

If you want to load the content of a Multipart file into a String, the easiest solution is:

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

Or, if you want to specify the charset:

String content = new String(file.getBytes(), StandardCharsets.UTF_8); 

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

like image 164
OlivierTerrien Avatar answered Sep 28 '22 01:09

OlivierTerrien


First, this is not related to Spring, and, second, you don't need to save the file to parse it.

To read the content of a Multipart file into a String you can use Apache Commons IOUtils class like this

ByteArrayInputStream stream = new   ByteArrayInputStream(file.getBytes()); String myString = IOUtils.toString(stream, "UTF-8"); 
like image 43
Rodrigo Villalba Zayas Avatar answered Sep 28 '22 01:09

Rodrigo Villalba Zayas