我正在使用springmvchibernatemysql。每当我在项目中上载文件时,数据库就不会以HTML格式保存,我希望上载该文件的用户保持数据库的格式。我该怎么办?

上载一种在上载期间控制器调用的方法。除了代码之外,任何一般性想法都将不胜感激。

private String getContentDescription(MultipartFile file, Long contentCategoryId) {
  StringBuffer contentDescription = new StringBuffer();
  ContentHandler textHandler = new BodyContentHandler(-1);
  InputStream input = null;
  try {
    input = file.getInputStream();
    Metadata metadata = new Metadata();
    this.parser.parse(input, textHandler, metadata, new ParseContext());
    input.close();
  } catch (IOException | SAXException | TikaException e) {
    LOGGER.debug("Unable to read uploaded document", e);
  }
  String returnString = "";
  if (null != textHandler) {
    if (contentCategoryId==3 && contentCategoryId==4) {
      String contentText = textHandler.toString();
      returnString = contentText.substring(0, Math.max(0, contentText.length()));
    } else {
      String contentText = textHandler.toString();
      returnString = contentText.substring(0, Math.min(1200, contentText.length()));
    }
  }
  return returnString;
}

最佳答案

您正在使用Tika解析HTML。 BodyContentHandler将仅返回在标记中找到的HTML,而不包含其他任何内容。您要做的就是读取整个文件。尝试这样的事情:

private String getContentDescription(MultipartFile file, Long contentCategoryId) {
    try (InputStream inputStream = file.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
        StringBuilder sb = new StringBuilder();

        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append('\n');
        }
        return sb.toString();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return null;
}

10-06 09:04
查看更多