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

时间:2015-07-13 21:09:41

标签: java spring multipartform-data

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?

3 个答案:

答案 0 :(得分:11)

如果要将Multipart文件的内容加载到String中,最简单的解决方案是:

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

或者,如果要指定字符集:

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

但是,如果你的文件太大,这个解决方案可能不是最好的。

答案 1 :(得分:5)

首先,这与Spring无关,其次,您不需要保存文件来解析它。

要将Multipart文件的内容读入String,您可以使用Apache Commons像这样的IOUtils类

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

答案 2 :(得分:0)

给出的答案是正确的,但最上面的答案说这对于大文件来说效率不高,原因是它会将整个文件保留在内存中,这意味着如果您上传2gb文件,它将消耗这么多的内存。代替这样做,我们可以逐行读取文件 ,而Apache Commons IO为此提供了一个不错的API。

LineIterator it = FileUtils.lineIterator(theFile, "UTF-8");
try {
    while (it.hasNext()) {
        String line = it.nextLine();
        // do something with line
    }
} finally {
    LineIterator.closeQuietly(it);
}

source