2017-01-13 40 views
0

我正在使用springmvc,hibernatemysql。每当我上传一个文件在我的项目中的数据库不保存为HTML格式,我希望那个用户上传文件,数据库应该保持格式。我该怎么办?数据库无法以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; 
} 
+1

上面的代码如何与保存数据库中的文本相关? –

+0

它只是控制器在保存数据期间调用的一种方法。这可能没有帮助,但任何建议或任何想法都会帮助我。对不起,有任何错误。 –

+0

那么你是否检查这种方法是否会破坏你的字符串? –

回答

0

应该从应用程序端点分析此问题。

  1. 您要发送到服务的请求应该是UTF-8

  2. 的数据应该UTF-8,直到你坚持下去的数据

    DB处理。

  3. 检查支持UnicodeCharacter Encoding

属性名= “javax.persistence.jdbc.url”
值=“JDBC连接字符串的:mysql://本地主机:3306/blogdatabase?了useUnicode =是&的characterEncoding = UTF-8"

  • 至S将数据存入数据库的列应该能够存储统计的特定数据。存储UTF-8数据将Db列转换为lob or blob类型。
  • 使用blow reference将JPA配置为相同。 JPA utf-8 characters not persisted

    Spring的配置文件Spring MVC UTF-8 Encoding

    春季多部分文件上传:http://javainsimpleway.com/spring-mvc-file-upload-single-and-multiple-files-upload/

    1

    您正在使用提卡来解析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; 
    } 
    
    +0

    我不理解的一件事是为什么返回值是否为空? –

    +0

    它不是。它返回sb.toString();如果它得到一个异常,它将返回null。 – teacurran

    +0

    !J?word/glossary/webSettings.xmlj0 {at_0JHR(/ \ Gid $ m5lz_im> Q42 mA