How to save generated PDF files to MySQL database using Java?

前端 未结 1 685

I have a Java class which is generating PDF file using iText library. Now as per my need I have to save this generated PDF file to MySQL database table but I have no idea ho

1条回答
  •  情深已故
    2021-01-14 21:44

    1. Datatype that you can use is BLOB.
    2. Convert the PDF file and persist the byte[] array in database.

      private byte[] getByteArrayFromFile(final Document handledDocument) throws IOException {
          final ByteArrayOutputStream baos = new ByteArrayOutputStream();
          final InputStream in = new FileInputStream(handledDocument);
          final byte[] buffer = new byte[500];
      
          int read = -1;
          while ((read = in.read(buffer)) > 0) {
              baos.write(buffer, 0, read);
          }
          in.close();
      
          return baos.toByteArray();
      }
      
    3. To insert it into DB If you are using any ORM tools you just have to map the column as blob and the tool will handle it for you. In case you are not using it then you can create a prepared statement. Statement has a method called setBlob() which will be useful. Consider the below example and create a normal insert query with blob column.

      String sql = "INSERT INTO testtable(stringcolumn, blobcolumn) VALUES(?,?)";
      
      PreparedStatement statement = conn.getConnection().prepareStatement(sql);
      statement.setLong(1, version);
      ByteArrayInputStream bais = new ByteArrayInputStream(getByteArrayFromFile(document));
      statement.setBlob(2, bais);          
      statement.execute();
      
      conn.commit();
      

    0 讨论(0)
提交回复
热议问题