【问题标题】:How to fix NullPointerException when uploading picture in database?在数据库中上传图片时如何修复 NullPointerException?
【发布时间】:2020-07-21 13:54:48
【问题描述】:

我想在数据库中上传一张图片,这是我的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>

这是我insert图片的方法:

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();

在 servlet 中,我只需调用此方法并将 request.getParameter("myimg") 作为参数(输入标记)传递。 经过一些研究,我认为我得到了这个错误,因为我没有把boundary 放在form 标签中。但我不知道该放什么数字,下一步该做什么,还是因为边界或其他原因而真的出错了?

【问题讨论】:

    标签: sql jsp exception servlets file-upload


    【解决方案1】:

    不要忘记在您的 servlet 中添加 @MultipartConfig 注释。此外,您正在将字符串传递给您的方法,而不是应该是 Part 。即:

      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")
    
         }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-04
      • 2019-12-06
      • 1970-01-01
      • 2020-01-15
      • 2015-04-23
      • 2013-06-26
      • 1970-01-01
      相关资源
      最近更新 更多