无法将图像存储到数据库中

时间:2013-08-19 13:31:03

标签: html mysql jsp

我创建了以下程序,当我按下提交按钮时,程序正在抛出FileNotFound异常。问题是由于JSP页面无法找到完整的图像路径。我调试了JSP程序,发现HTML表单只传递图像名称而没有路径,这就是为什么会出现问题。任何人都可以解决这个问题。

##################  SQL Query ######################################

    CREATE TABLE IMAGEMAIN(ID INTEGER,IMAGE BLOB) ;

##################  HTML  Form ######################

     <form name="frm" method="post" action="index.jsp">
     <input type="text" name="hint">
     <input type="file" name="user_file">
     <input type="submit">

################### JSP PAGE ########################

try
{ 
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    System.out.println("Connection loaded");
    Connection con = DriverManager.getConnection("jdbc:odbc:project","image","image");
    System.out.println("Connection created");
    String ll=request.getParameter("user_file");
    String lo=request.getParameter("hint");
    File imgfile = new File(ll);

    FileInputStream fin = new FileInputStream(imgfile);

    PreparedStatement pre = con.prepareStatement("insert into IMAGEMAIN (id,image) values(?,?)");
    pre.setString(1,lo);
    pre.setBinaryStream(2,fin,(int)imgfile.length());
    pre.executeUpdate();
    pre.close();
}

catch(Exception E)
{
    out.println("the eror is  "+ E);
}

1 个答案:

答案 0 :(得分:0)

您正在使用的FileInputStream(String)的构造函数需要一个文件名,这不起作用,因为在HTTP上传的文件中没有像这样工作的文件名 - 而是直接操作流。< / p>

根据此SO QA(jsp file upload issues),JSP不提供处理多部分HTTP请求的内置支持,因此如果不使用Apache Commons FileUpload之类的其他Java包,则无法处理上载的文件。

所以我建议您安装FileUpload,然后使用它来访问上传的文件。我不熟悉它,但这里有文档:http://commons.apache.org/proper/commons-fileupload/using.html