简体   繁体   English

如何使用Java和Spring MVC在SQL Server DB中上载文件

[英]How to upload a file in SQL Server DB using Java and Spring MVC

I have jsp with method="post" enctype="multipart/form-data"> in form tag, Spring MVC Controller with @RequestParam CommonsMultipartFile otherDocs, and below piece of code to insert file into DB 我在表单标签中有method="post" enctype="multipart/form-data"> @RequestParam CommonsMultipartFile otherDocs,带有@RequestParam CommonsMultipartFile otherDocs, Spring MVC Controller @RequestParam CommonsMultipartFile otherDocs,以及下面的代码片段,用于将文件插入DB

        PreparedStatement pstmt = null;

        try {
            String fileName = fileItem.getName().substring(fileItem.getName().lastIndexOf("\\")+1, fileItem.getName().length());

            File file = new File(fileItem.getName());
            FileInputStream fis = new FileInputStream(file);

            String sql = "INSERT INTO MyTable(formId, fileType, fileName, updateTime, updateUser, content) VALUES(?, ?, ?, getDate(), ?, ?)";

            pstmt = connection.prepareStatement(sql);          

            pstmt.setInt(1, id);
            int len = (int)file.length();

            if(fileItem.getContentType().endsWith(".document")){
                pstmt.setString(2, "Document");
            }else{
                pstmt.setString(2, "else");             
            }
            pstmt.setString(3, fileName);
            pstmt.setString(4, userLoggedIn);

            //pstmt.setBytes(5, bs);<------noted
            pstmt.setBinaryStream(5, fis, len);

            int count = pstmt.executeUpdate();
        } catch (Exception e) {             
            e.printStackTrace();            
        }finally{
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

I am getting " String or binary data would be truncated. " after firing executeUpdate() only when 5th parameter is set. 仅在设置了第5个参数后,在执行executeUpdate()之后,我得到“ 字符串或二进制数据将被截断。 I have tried running the query without 5th parameter which is running fine. 我尝试运行没有第5个参数的查询,该参数运行良好。

I tried with commented "noted" line as well, getting the same Data Truncation error. 我也尝试使用带注释的“注释”行,并得到相同的数据截断错误。

Thanks 谢谢

Jai i

如果将文件extern以其哈希值或类似名称保存在目录中,则将是很多更好的解决方案,在数据库中,您仅应随后保存其名称。

Database table's column was required to be changed from varbinary to varbianry(max). 需要将数据库表的列从varbinary更改为varbianry(max)。 This change made my code to work :) 这项更改使我的代码可以工作了:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM