使用html / jsp中的文件上载将blob图像插入数据库

时间:2014-02-14 08:52:39

标签: mysql image jsp

我是jsp的新手。我有一个名为employee的表现在我想使用名称request参数将图像插入数据集。该表已经有name,{{ 1}},ageidphonenumberemail as fields.image是我现在创建的新字段。当使用新的blob图像更新图像字段时,它不是显示错误但图像未插入。这是我的尝试:

password

1 个答案:

答案 0 :(得分:0)

  <% @ page import="java.io.*" %>
   <% @ page import="java.sql.*" %>
   <% @ page import="java.util.zip.* "%>
  <%
     String saveFile="";
     String contentType=request.ContentType();
     if((contentType != null) &&(contentType.indexOf("multipart/form-data")>=0))
      {
       DataInputStream in= new DataInputStream(request.getInputStream());
      int formDataLength=request.getContentLength();
      byte dataBytes[]= new byte[formDataLength];
      int byteread=0;
      int totalbyteread=0;
      while(totalbyteread<formDataLength)
      {
      byteread=in.read(dataBytes,totalbyteread,formDataLength);
      totalbyteread =byteread+1;
       }
      String file= new String(dataBytes);
      saveFile=file.subString(file.indexOf("filename=\"")+10);
       saveFile= saveFile.subString(0,saveFile.indexOf("\n"));
        saveFile=saveFile.subString(saveFile.lastIndexOf("\\")+1,saveFile.indexOf("\""));

      int lastIndex=contentType.lastIndexOf("=");
      String boundry=contentType.subString(lastIndex+1,contentType.length());
      int pos;
      pos=file.indexOf("filename=\"");
      pos=file.indexOf("n\",pos)+1;
      pos=file.indexOf("n\",pos)+1;
      pos=file.indexOf("n\",pos)+1;
      pos=file.indexOf("n\",pos)+1;
      int boundrylocation=file.indexOf(boundry,pos)-4;
      int startpos=((file.subString(0,pos)).getBytes()).length;
      int endpos=((file.subString(0,boundryloction)).getBytes()).length;
      File ff= new File(saveFile);
      FileOutputStream fileout= new FileOutputStram(ff);
      fileout.write(dataBytes,startpos,(endpos-startpos));
      fileout.flush();
      fileout.close();
      %>
      <Br><table border="2"><tr><td><b>You have successfully upload the file:</b>
     <%out.println(saveFile);%></td></tr></table>
     <%
     Connection connection = null;
    String connectionURL = "jdbc:mysql://localhost:3306/praveen";
    PreparedStatement pstatement = null;
    FileInputStream inputStream = fis;
    ResultSet rs=null;
    try
     {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
    connection = DriverManager.getConnection(connectionURL, "root", "bulbultara");
     File f= new File(saveFile);
     pstatement=connection.prepareStatement("insert into employee(name of image cloumn) values(?)");
      pstatement.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
     int s = pstatement.executeUpdate();
         if(s>0){
           System.out.println("Uploaded successfully !");
       }
      else{
      System.out.println("Error!");
       }
          }
        catch(Exception e){e.printStackTrace();}
      }
     }

   %>