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

独自空忆成欢 提交于 2019-12-05 14:03:17

问题


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?


回答1:


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(), "UTF-8");

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




回答2:


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");


来源:https://stackoverflow.com/questions/31393553/how-to-read-a-multipart-file-as-a-string-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!