我想使用 Advanced Rest Client 从我的桌面发布一个文本文件。 这是我的 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());
}
这不会返回任何字节长度或文件大小的值。我想将文件值读取到 StringBuffer。有人可以提供有关此的指示吗?我不确定在将其解析为字符串之前是否需要保存此文件。如果是这样,我如何将文件保存在工作区中?
最佳答案
如果要将Multipart文件的内容加载到String中,最简单的解决方案是:
String content = new String(file.getBytes());
或者,如果你想指定字符集:
String content = new String(file.getBytes(), StandardCharsets.UTF_8);
但是,如果您的文件很大,这个解决方案可能不是最好的。
关于java - 如何在 Spring 中将 Multipart 文件作为字符串读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31393553/