JDBC把图片放进数据库
代码
Servlet
@WebServlet(
name = "Servlet",
urlPatterns = "/Servlet",
loadOnStartup = 1
)//其他配置没有问题
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String sql = "INSERT INTO blob VALUES(DEFAULT,?,?)";
JDBC.blob(connection, sql, "/resource/1.png", "image1");
JDBC.disconnect(connection);
}
JDBC类
public static boolean blob(Connection connection, String sql, String resource, Object... args) {
PreparedStatement ps = null;
try {
ps = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
//主要就这一句,resource是传入的文件路径字符串
FileInputStream fis = new FileInputStream(new File(resource));
ps.setBlob(args.length + 1, fis);
ps.execute();
return true;
} catch (SQLException | FileNotFoundException e) {
e.printStackTrace();
return false;
} finally {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<form action="Servlet" method="post">
<input type="submit" value="submit">
<img src="resource/1.png" alt="dada">
</form>
</body>
</html>
其他说明
在index.jsp界面可以显示图片
configurations配置好了,下面的context和上面代码里填的一样
文件已经在artifacts文件夹下面,但是找不到图片
在浏览器中输入http://localhost:8080/resource/1.png或者http://localhost:8080/JavaWeb_war_exploded/resource/1.png都可以找到图片
试了其他路径都找不到~~
../../resource/1.png
/JavaWeb_war_exploded/resource/1.png
/JavaWeb_war_exploded/index.jsp
index.jsp