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

标签 mysql image jsp

我是 jsp 新手。我有一个名为 employee 的表,现在我想使用名称作为 request 参数将图像插入到数据存储中。该表已经有 姓名,年龄,id,电话号码,电子邮件,密码 因为 fields.image 是我现在创建的新字段。当使用新的 blob 图像更新图像字段时,它没有显示错误,但图像没有插入。这是我的尝试:

    // My form to fileupload

    <form name="frm" action="Image.jsp"  method="post">
        <center>Name:<input type="text" name="name"><br></center><br>

     <center><br><br>&nbsp;&nbsp;<input type="submit" value="Submit"></center>
   </form>

    //(Image.jsp )My pgogram to get file from client and store in database 

     <%@ page import="java.sql.*" %>
     <%@ page import="org.apache.commons.fileupload.*"%>
     <%@ page import="org.apache.commons.io.output.*"%>
     <%@ page import="org.apache.commons.fileupload.servlet.*"%>
     <%@ page import="org.apache.commons.fileupload.disk.*"%>
     <%@ page import="java.io.*"%>
 <%@ page import="java.util.*"%>
  <html>
      <body>
    <%
        Connection connection = null;
        String connectionURL = "jdbc:mysql://localhost:3306/praveen";
        PreparedStatement pstatement = null;
        FileInputStream inputStream = null;
        int insertQuery = 0;

         byte[] b = null;

        Class.forName("com.mysql.jdbc.Driver").newInstance();
        connection = DriverManager.getConnection(connectionURL, "root", "bulbultara");

         String sql = "update employee set image=? where name=? ";
        pstatement = connection.prepareStatement(sql);
        pstatement.setString(2, request.getParameter("name"));
        DiskFileItemFactory factory = new DiskFileItemFactory();

         ServletFileUpload sfu = new ServletFileUpload(factory);
         List items = sfu.parseRequest(request);

        Iterator iter = items.iterator();

         while (iter.hasNext()) {
         FileItem item = (FileItem) iter.next();
         if (!item.isFormField()) {
         b = item.get();
            }
           }

        pstatement.setBytes(1, b);
        insertQuery = pstatement.executeUpdate();
        pstatement.close();
        connection.close();

      %>

       <a href="Login.jsp"><input type="submit" value="Login"></a>
     </body>
  </html>

最佳答案

  <% @ 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();}
      }
     }

   %>

关于mysql - 使用 html/jsp 中的文件上传将 blob 图像插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21774726/

相关文章:

javascript - 如何在 Struts2 自动完成器操作中传递 javascript 对象?

MYSQL:将数据内文件...加载到表中...; DATETIME 字段变为 0000:00:00 00:00:00

mysql - 添加最新结果

java - 如何将图片导入到Android项目中?

jQuery 图像预加载/缓存停止浏览器

java - 是否可以将 if 条件放入 <s :select> tag? 的 listValue 内

java - If 语句中的 JSP session

php - 如何为 Google 多折线图(php、mysql)做 mysql LEFT JOIN?

php - 删除 id 与其他表中相同的行

php - 将文件名作为 post 变量不好吗?