[英]How to upload a file in SQL Server DB using Java and Spring MVC
我在表單標簽中有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();
}
}
僅在設置了第5個參數后,在執行executeUpdate()之后,我得到“ 字符串或二進制數據將被截斷。 ” 我嘗試運行沒有第5個參數的查詢,該參數運行良好。
我也嘗試使用帶注釋的“注釋”行,並得到相同的數據截斷錯誤。
謝謝
i
如果將文件extern以其哈希值或類似名稱保存在目錄中,則將是很多更好的解決方案,在數據庫中,您僅應隨后保存其名稱。
需要將數據庫表的列從varbinary更改為varbianry(max)。 這項更改使我的代碼可以工作了:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.