[英]How to save doc, pdf, and image files to mysql database using java?
[英]How to save generated PDF files to MySQL database using Java?
我有一個 Java 類,它使用iText庫生成 PDF 文件。 現在根據我的需要,我必須將此生成的 PDF 文件保存到 MySQL 數據庫表中,但我不知道該怎么做。
我的擔憂是:
目前我正在生成PDF文件並將其存儲到本地磁盤的硬編碼文件路徑中。
這是我用 Java 編寫的 PDF 生成代碼:
OutputStream file = new FileOutputStream(new File("D://timer.pdf"));
Document document = new Document();
PdfWriter.getInstance(document, file);
//Inserting Table in PDF
PdfPTable table = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Paragraph("Java4s.com"));
cell.setColspan(3);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setPadding(10.0f);
cell.setBackgroundColor(new BaseColor(140, 221, 8));
table.addCell(cell);
table.addCell("Name");
table.addCell("Address");
table.addCell("Country");
table.addCell("Java4s");
table.addCell("NC");
table.addCell("United States");
table.setSpacingBefore(30.0f); // Space Before table starts, like margin-top in CSS
table.setSpacingAfter(30.0f); // Space After table starts, like margin-Bottom in CSS
//Inserting List in PDF
List list = new List(true, 30);
list.add(new ListItem("Java4s"));
list.add(new ListItem("Php4s"));
list.add(new ListItem("Some Thing..."));
//Text formating in PDF
Chunk chunk = new Chunk("Welecome To Java4s Programming Blog...");
chunk.setUnderline(+1f, -2f);//1st co-ordinate is for line width,2nd is space between
Chunk chunk1 = new Chunk("Php4s.com");
chunk1.setUnderline(+4f, -8f);
chunk1.setBackground(new BaseColor(17, 46, 193));
//Now Insert Every Thing Into PDF Document
document.open();//PDF document opened........
document.add(Chunk.NEWLINE); //Something like in HTML :-)
document.add(new Paragraph("Dear Java4s.com"));
document.add(new Paragraph("Document Generated On - " + newDate().toString()));
document.add(table);
document.add(list); //In the new page we are going to add list
document.close();
file.close();
System.out.println("Pdf created successfully..");
請幫我。
提前致謝。
BLOB
。 轉換 PDF 文件並將byte[]
數組保存在數據庫中。
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(); }
將其插入數據庫 如果您使用任何 ORM 工具,您只需將該列映射為 blob,該工具將為您處理它。 如果您不使用它,那么您可以創建一個准備好的語句。 Statement 有一個名為 setBlob() 的方法,它將很有用。 考慮下面的示例並使用 blob 列創建一個普通的插入查詢。
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.