正如我在标题中提到的,我想将图像上传到数据库字段中。所以,无论我用我的编码部分做了什么。我在这里分享。我不认为,我的代码会有任何问题,因为我在屏幕上输出正确。但是,问题是,当我打开数据库时,它显示了一些不同的输出。当我尝试执行select * from PIC
时,我不知道数据库中出了什么问题。然后,PIC
列显示了一些意外结果。不知道我的图像是否插入到桌面中。
谢谢!!!
的index.jsp
<html>
<head>
<title>Upload</title>
</head>
<body>
<form action="upload" enctype="multipart/form-data" method="post">
<table width="400" align="center">
<tr><td>UserName :</td><td><input type="file" name="userid" id="userid" /></td></tr>
<tr><td><input type="Submit" value="Upload" style="width: 100px; height:30px;"/></td></tr>
</table>
</form>
</body>
这是我的servlet页面:
upload.java
package fileupload;
import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.regex.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class upload extends HttpServlet {
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
out.println("File Not Uploaded");
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try {
items = upload.parseRequest(request);
out.println("items: " + items);
} catch (FileUploadException e) {
e.printStackTrace();
}
FileItem file = (FileItem) items.get(0);
// out.print(file);
Connection conn = null;
String connstr = "jdbc:oracle:thin:@localhost:1521/XE";
String uname = "epolicia";
String password = "admin";
String driver = "oracle.jdbc.OracleDriver";
String sql = null;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(connstr, uname, password);
// FileInputStream fs = new FileInputStream(savedFile);
sql = "INSERT INTO pic(pic) VALUES(?)";
PreparedStatement st = conn.prepareStatement(sql);
// st.setInt(1,1);
st.setBinaryStream(1, file.getInputStream(), (int) file.getSize());
int rs = st.executeUpdate();
if (rs > 0) {
out.println("Query Executed Successfully++++++++++++++");
}
conn.close();
} catch (Exception e) {
out.println(e.getMessage());
}
}
}
}
页面成功运行,没有任何异常。将不胜感激。
答案 0 :(得分:4)
最后,我找到了解决方案。谢谢大家。我按照网站上提到的步骤,链接,我分享了相同的链接。所以,其他人将从中受益。
Upload photos into Oracle BLOB column from Java Servlet and listing photos
因为,图片正在 blob
类型中插入,binary large object
无法在sql*plus
上显示。这就是显示[datatype]
的原因。
答案 1 :(得分:1)
你可以在mysql中使用数据类型Midblob或blob。存储图像。 midbolb数据类型存储的大小超过blob ..