首页 > 解决方案 > 无法将图像存储在 mysql 数据库中。空指针异常

问题描述

<body>
<form name="frm" action="saveImage.jsp" enctype="multipart/form-data" method="post">
 <input type="file" name="uProperty" /> <br>
 <input type="submit" name="goUpload" value="Upload" />
</form>
</body>

Above is my html code.

<%
Connection conn=null;
PreparedStatement pstmt = null;
ResultSet rs=null;
String url="jdbc:mysql://localhost:3306/amber";
FileInputStream fis=null;

String myloc=request.getParameter("pic"); 
out.print("mylocation="+myloc);
File image= new File(myloc);
out.println(image);

try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn=DriverManager.getConnection(url, "root", "sameer0207");


pstmt = conn.prepareStatement("insert into image(image) " + "values(?)");

fis=new FileInputStream(image);

pstmt.setBinaryStream(1,fis, image.length());
int count = pstmt.executeUpdate();
if(count>0)
{
out.println("insert successfully");
}
else
{
out.println("not successfully");
}
}catch(Exception e){}

%>

这是我试图将值图像存储在数据库 mysql 中的 jsp 文件。错误在“文件图像=新文件(myloc);”行中 显示的是哪个浏览器。当我打印地址时,只有文件名不是完整地址。当我将地址放入“File image= new File("C:\images\1.png");”中时,它运行正常。请帮忙。

标签: databasejspblob

解决方案


您至少必须添加空检查,因为new File(null);总是抛出 NPE,例如:

if(myloc != null) {
    File f = new File(myloc);
    if (f.exists()) {
      ...

推荐阅读