如何在jsp和servlet中将多个图像上传到mysql

时间:2015-01-19 12:10:24

标签: mysql jsp file-upload

我正在尝试使用以下代码创建匹配以下问题(图像到文本),

MyCSS.css

<style type="text/css">

#container {
  width: 600px;
}

#container div {
  float: left;
  height: 300px;
  width: 300px;
}

</style>

MyJspPage.jsp

    <div id="container">
     <div>
      <img alt="Image1" id="Image1" src="" width="200px" height="110px"><br><br>
      <img alt="Image2" id="Image2" src="" width="200px" height="110px"><br><br>
      <img alt="Image3" id="Image3" src="" width="200px" height="110px"><br><br> 
      <img alt="Image4" id="Image4" src="" width="200px" height="110px"><br><br>
      <img alt="Image5" id="Image5" src="" width="200px" height="110px"><br><br>
      </div>
      <div>
      <input type="text" id="ImgAtxt1" name="ImgAtxt1" placeholder="Type answer 1"><br><br>
      <input type="text" id="ImgAtxt2" name="ImgAtxt2" placeholder="Type answer 2"><br><br>
      <input type="text" id="ImgAtxt3" name="ImgAtxt3" placeholder="Type answer 3"><br><br>
      <input type="text" id="ImgAtxt4" name="ImgAtxt4" placeholder="Type answer 4"><br><br>
      <input type="text" id="ImgAtxt5" name="ImgAtxt5" placeholder="Type answer 5"><br><br>

      </div>
  <input type="file" id="files" name="files[]" accept="image/gif,image/jpeg"/>
<input type="button" id="ADDdbbt" value="Add To DB"><br>
<input type="button" id="clearId" value="Clear">  
    </div>

MYSCript:

document.querySelector('#files').addEventListener('change', handleFileSelect, false);


function handleFileSelect(evt) {

    var files = evt.target.files; // FileList object
   // alert("1");
   // Loop through the FileList and render image files as thumbnails.
   for (var i = 0, f; f = files[i]; i++) {

     // Only process image files.
     if (!f.type.match('image.*')) {
       continue;
     }

     var reader = new FileReader();   
     reader.onload = (function(theFile) {
       return function(e) {
           var count=$('#imginsert').val();
                if(count==1){
                    //alert("if");
                $('#Image1').attr("src",e.target.result);
                $('#imginsert').val('2');
                $('#ImgAtxt1').before("<br><br>");
                }
                else if(count==2)
                {
                    //alert("else if 1");
                    $('#Image2').attr("src",e.target.result);
                    $('#imginsert').val('3');
                    $('#ImgAtxt2').before("<br><br><br>");
                }
                else if(count==3)
                {
                    //alert("else if 2");
                    $('#Image3').prop("src",e.target.result);
                    $('#imginsert').val('4');
                    $('#ImgAtxt3').before("<br><br><br>");
                }
                else if(count==4)
                {
                    $('#Image4').prop("src",e.target.result);
                    $('#imginsert').val('5');
                    $('#ImgAtxt4').before("<br><br><br><br>");
                }
                else if(count==5)
                {
                    $('#Image5').prop("src",e.target.result);
                    $('#imginsert').val('6');
                    $('#ImgAtxt5').before("<br><br><br><br>");
                }
                else
                {
                    alert("You can upload only 5 images.");
                }

       };

     })(f); 

     // Read in the image file as a data URL.
     reader.readAsDataURL(f);
   }


 }

最后我把它作为我期望的视图如下图所示, enter image description here

现在我想将5个上传的图像添加到mysql。如何做到这一点?

我已使用以下代码将单个图像添加到mysql,

package TeachChapter;

import java.io.IOException;  
import java.io.InputStream;  
import java.sql.*;

import javax.servlet.ServletException;  
import javax.servlet.annotation.MultipartConfig;  
import javax.servlet.annotation.WebServlet;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
import javax.servlet.http.Part;  


@WebServlet("/fileUpload")  
@MultipartConfig(maxFileSize = 16177215) // upload file up to 16MB  
public class ImagesADDToDBServlet extends HttpServlet {  

    private static final long serialVersionUID = -1623656324694499109L;  


    public ImagesADDToDBServlet() {  

    }  

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

        // gets values of text fields  
        String firstName = request.getParameter("firstName");  
        String lastName = request.getParameter("lastName");  

        InputStream inputStream = null;  

        // obtains the upload file part in this multipart request  
        Part filePart = request.getPart("photo");  
        if (filePart != null) {  
            // debug messages  
             String header=filePart.getHeader("content-disposition");
             String filename = header.substring(header.indexOf("filename=\"")).split("\"")[1];  //getting filename


            System.out.println(filePart.getName());  
            System.out.println(filePart.getSize());  
            System.out.println(filePart.getContentType()); 
            System.out.println(filename); 

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

        String message = null; // message will be sent back to client  

        try {  
            // constructs SQL statement 
            try {
                Class.forName("com.mysql.jdbc.Driver");

            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");

            String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";  
            PreparedStatement statement = con.prepareStatement(sql);  
            statement.setString(1, firstName);  
            statement.setString(2, lastName);  

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

            // sends the statement to the database server  
            int row = statement.executeUpdate();  
            if (row > 0) {  
                message = "Image is uploaded successfully into the Database";  
            }  
        } catch (SQLException ex) {  
            message = "ERROR: " + ex.getMessage();  
            ex.printStackTrace();  
        }  
        // sets the message in request scope  
        request.setAttribute("Message", message);  

        // forwards to the message page  
        getServletContext().getRequestDispatcher("/ImagesAdddToDBREsut.jsp").forward(  
                request, response);  
    }  
}

有人告诉我如何将5个上传的图像插入数据库?

0 个答案:

没有答案