如何使用html,servlet将图像插入mysql

时间:2018-12-06 14:50:17

标签: java html mysql jsp servlets

我正在尝试使用html和mysqlservlet表中插入3张图像,但它仅存储一张图像。

这是html表单。

<form action="datahandler.java" method="post" enctype="multipart/form-data" role="form">
<input  maxlength="100" type="text" name="name" class="form-control" placeholder=""  />
<input type="file" id="files"  name="image1" accept="image/*" /> 
<input type="file" id="files"  name="image2" accept="image/*" /> 
<input type="file" id="files"  name="image3" accept="image/*" /> 
</form>

当我上传图像并将其发送到服务器时-datahandler.java

package controller;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;


 @MultipartConfig(maxFileSize = 16177216) // upto 16 MB
public class DataHandler extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Connection conn=null;
        String dbPath = "";
        String username = "";
        String password = "";

        String name=request.getParameter("name");

        // Create a new file upload handler
        InputStream inputStream = null; 

        // obtains the upload file part in this multipart request
        Part parts1 = request.getPart("image1");
        Part parts2 = request.getPart("image2");
        Part parts3 = request.getPart("image3");

         if (parts1 != null) 
        {
            // prints out some information for debugging
            System.out.println(parts1.getName());
            System.out.println(parts1.getSize());
            System.out.println(parts1.getContentType());

            // obtains input stream of the upload file
            inputStream = parts1.getInputStream();
        }
         if (parts2 != null) 
        {
            // prints out some information for debugging
            System.out.println(parts2.getName());
            System.out.println(parts2.getSize());
            System.out.println(parts2.getContentType());

            // obtains input stream of the upload file
            inputStream = parts2.getInputStream();
        }
         if (parts3 != null) 
        {
            // prints out some information for debugging
            System.out.println(parts3.getName());
            System.out.println(parts3.getSize());
            System.out.println(parts3.getContentType());

            // obtains input stream of the upload file
            inputStream = parts3.getInputStream();
        }
         if (parts4 != null) 
        {
            // prints out some information for debugging
            System.out.println(parts4.getName());
            System.out.println(parts4.getSize());
            System.out.println(parts4.getContentType());

            // obtains input stream of the upload file
            inputStream = parts4.getInputStream();
        }


          try{

            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(dbPath, username, password);

           PreparedStatement pst = conn.prepareStatement("insert into user(name,image1,image2,image3) values(?,?,?,?)");

           pst.setString(1,name);


            if (inputStream != null)
            {
                // fetches input stream of the upload file for the blob column
                pst.setBlob(2, inputStream);
            }
            if (inputStream != null)
            {
                // fetches input stream of the upload file for the blob column
                pst.setBlob(3, inputStream);
            }
            if (inputStream != null)
            {
                // fetches input stream of the upload file for the blob column
                pst.setBlob(4, inputStream);
            }

           int i = pst.executeUpdate();  
              if(i!=0){  
                out.println("Record has been inserted");  
                   request.getRequestDispatcher("success.jsp").forward(request, response);

              }  
              else{  
                out.println("failed to insert the data"); 
                request.getRequestDispatcher("failed.jsp").forward(request, response);
               }  
        }
       catch(Exception e){
            out.print(e);
        }
    finally{
                try {
                    conn.close();
                } catch (SQLException ex) {
                    Logger.getLogger(ImageStoreToDatabase.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }

  }

Servlet正在获取所有三个图像。系统会打印其信息,但是当它存储到数据库时,image3将存储在image1列中,而image2和image3为空列。请对此提供解决方案。

1 个答案:

答案 0 :(得分:0)

这是因为您将所有部分都设置为相同的InputStream。您必须创建不同的InputStream变量,例如:

InputStream inputStream1 = parts1.getInputStream(); InputStream inputStream2 = parts2.getInputStream(); InputStream inputStream3 = parts3.getInputStream();

当您在pst.setBlob(...)中设置值时,您将执行相同的操作。 否则,您将为每列设置相同的图像。祝你好运!