@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);
}
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();
}
}
}
<%@ 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>
../../resource/1.png
/JavaWeb_war_exploded/resource/1.png
/JavaWeb_war_exploded/index.jsp
index.jsp
src图片路经使用绝对路经试试,加上<%=request.getContextPath() %>,即类似:
<img src=“<%=request.getContextPath() %>/resource/1.png" alt="dada">
https://blog.csdn.net/jacksonzhou88/article/details/62508188