【问题标题】:How to read a Multipart file as a string in Spring?如何在 Spring 中将 Multipart 文件作为字符串读取?
【发布时间】:2015-07-13 21:09:40
【问题描述】:

我想使用 Advanced Rest Client 从我的桌面发布一个文本文件。 这是我的控制器:

@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());

}

这不会返回任何字节长度或文件大小的值。我想将文件值读取到 StringBuffer。有人可以提供有关此的指示吗?我不确定在将其解析为字符串之前是否需要保存此文件。如果是这样,我如何将文件保存在工作区中?

【问题讨论】:

  • 您应该避免一次检索所有字节。相反,使用MultiPartFile#getInputStream 并使用该流来填充您的StringBuilder(您不需要使用StringBuffer)或任何其他方式来使用数据。
  • 嗨..你得到解决方案了吗。请添加解决方案。

标签: java spring multipartform-data


【解决方案1】:

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

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

或者,如果你想指定字符集:

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

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

【讨论】:

  • 这对我不起作用,不返回 UTF 字符。
【解决方案2】:

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

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

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

【讨论】:

  • MultipartFile 是 Spring 类型——所以问题与 Spring 有关。但是一旦你调用getBytes(),你就进入了通用Java的领域。
【解决方案3】:

给定的答案是正确的,但最重要的答案说它对大文件效率不高,原因是它将整个文件保存在内存中,这意味着如果您上传 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 2016-06-02
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多