gpt4 book ai didi

java - 我无法使用 jdbc 将 blob 图像插入 oracle 数据库

转载 作者:行者123 更新时间:2023-11-30 12:08:46 25 4
gpt4 key购买 nike

我正在尝试使用 JDBC 将图像上传到 oracle DB。我得到一个异常“系统找不到指定的文件”

这是代码

<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.*"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.util.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>

<%
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("Connection loaded");
Connection c=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","system","oracle123");
System.out.println("Connection created");
String ll=request.getParameter("user_file");
String id=request.getParameter("id");
File imgfile = new File(ll);//till this pint the code is running correctly
FileInputStream fin = new FileInputStream(imgfile);//working in this point...
PreparedStatement pre = c.prepareStatement("insert into PHOTOS (id,photo) values(?,?)");
pre.setString(1,id);
pre.setBinaryStream(2,fin,(int)imgfile.length());
pre.executeUpdate();
pre.close();
}catch(Exception E){out.println("the eror is "+ E);}
%>
</body>
</html>

最佳答案

假设您来自多部分 HTTP POST,例如

<form action="upload.jsp" method="post" enctype="multipart/form-data">
<input type="text" name="id" size="10" />
<br />
<input type="file" name="user_file" size = "50" />
<br />
<input type="submit" value="Upload File" />
</form>

你需要一个文件上传组件,比如 org.apache.commons.fileupload 之类的

Class.forName("oracle.jdbc.driver.OracleDriver");

DiskFileItemFactory factory = new DiskFileItemFactory();
// Set memory threshold - beyond which files are stored in disk
factory.setSizeThreshold(1024*1024); // 1Mb
// Set temporary location to store files
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

ServletFileUpload upload = new ServletFileUpload(factory);

try (Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle123")) {
String id = null;
InputStream photo = null;
int photoSize = 0;

for (FileItem item : upload.parseRequest(request)) {

if (item.isFormField()) {
if (item.getFieldName().equals("id")) {
id = item.getString();
}
} else {
if (item.getFieldName().equals("user_file")){
photo = item.getInputStream();
photoSize = item.getSize();
}
}
}

assert (id!=null);
assert (photo!=null);

try (PreparedStatement pre = c.prepareStatement("insert into PHOTOS (id,photo) values(?,?)")) {
pre.setString(1,id);
pre.setBinaryStream(2,item.getInputStream(),item.getSize());
pre.executeUpdate();
}
}

关于java - 我无法使用 jdbc 将 blob 图像插入 oracle 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54194176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com