nemke nemke
nemke nemke

Reputation: 191

How to fix NullPointerException when uploading picture in database?

I want to upload a picture in database, and this is my jsp:

    <body>
    <form action="addbooka" method="POST" enctype="multipart/form-data">
        Title:<input type="text" value="${title}" name="title"> <br>
        Description: <input type="text" value="${description}" name="description"><br>
        Price: <input type="text" value="${price}" name="price"><br>
        Picture: <input type="file" name="myimg"><br>
        <button type="submit">Add</button>          
    </form>       
</body>

And this is method where i insert picture:

public static void insertImage(String myImage) throws Exception {
    try {
        String insertImage = ("insert into image(image) values(?)");
        PreparedStatement ps = DataBaseConnection.get().prepareStatement(insertImage);           
        File file = new File(myImage);                     
        InputStream in = new FileInputStream(file);
        ps.setBlob(1, in);
        ps.executeUpdate();

In servlet i just call this method and pass request.getParameter("myimg") as an argument(input tag). After some research i think i get this error because i did't put boundary in form tag. But i can't wrap my head around what numbers to put, what to do next or is it really error because of boundary or something else?

Upvotes: 0

Views: 85

Answers (1)

Swati
Swati

Reputation: 28522

In your servlet don't forget to put @MultipartConfig annotation.Also , you are passing string to your method instead that should be Part . i.e :

  int row=0;
  InputStream inputStream = null; // input stream of the upload file
  // obtains the upload file part in this multipart request
    Part filePart = request.getPart("myimg");//get image
    insertImage(filePart)//pass to method

 public static void insertImage(Part filePart) throws Exception {
      String insertImage = ("insert into image(image) values(?)");
    PreparedStatement ps = DataBaseConnection.get().prepareStatement(insertImage); 
    if (filePart != null) {
      
        // obtains input stream of the upload file
        inputStream = filePart.getInputStream();
      
    }
   if (inputStream != null) {
            // fetches input stream of the upload file for the blob column
            ps.setBlob(1, inputStream);
    }
    row = ps.executeUpdate();
        if (row > 0) {
  out.println("done")

     }
  }

Upvotes: 1

Related Questions