在数据库中上传图片时如何修复nullpointerexception?

nx7onnlm  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(377)

我想在数据库中上传一张图片,这是我的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") 作为参数(输入标记)。经过一些研究,我认为我得到这个错误,因为我没有把 boundaryform 标签。但我不知道该放什么数字,下一步该做什么,或者它真的是因为边界或其他原因而出错吗?

uqdfh47h

uqdfh47h1#

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

     }
  }

相关问题