我从HTML
上传文件如何使用servlet将pdf文件存储在postgresql数据库中?
<center><form action="pdf" method="post" enctype="multipart/form-data">
<b>Upload Certificate</b>
<input type="file" name="file"/></center>
<center> <input type="submit" /></center>
</form>
在提交表单,PDF格式的Servlet被调用。在servlet内部,解析请求对象并使用InputStream读取文件(pdf),如下面的代码所示。
protected void doPost(HttpServletRequest paramHttpServletRequest, HttpServletResponse paramHttpServletResponse)
throws ServletException, IOException
{
try
{
List localList = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(paramHttpServletRequest);
for (FileItem localFileItem : localList)
{
String str1 = localFileItem.getFieldName();
String str2 = FilenameUtils.getName(localFileItem.getName());
System.out.println("fieldname:" + str1);
System.out.println("filename:" + str2);
InputStream localInputStream = localFileItem.getInputStream();
try
{
PdfReader localPdfReader = new PdfReader(localInputStream);
paramHttpServletResponse.sendRedirect("takedetails.jsp");
}
catch (InvalidPdfException localInvalidPdfException)
{
paramHttpServletResponse.sendRedirect("upload.jsp");
}
}
}
catch (FileUploadException localFileUploadException)
{
throw new ServletException("Cannot parse multipart request.", localFileUploadException);
}
}
如您所见,我使用InputStream对象检查文件格式为pdf。
现在我想把这个pdf文件保存到postgresql数据库。我应该在postgresql中使用哪些字段,以及如何从InputStream对象中获取文件以将其存储在数据库中?
而不是使用内存中的字节[],请考虑使用临时文件或智能缓冲区类,该缓冲区类在知道从内存缓冲区切换到临时文件时会超过特定大小。另外,虽然它可能对你无关紧要,但是bytea限制为1GB。对于更大的文件,将它们存储在数据库之外并只存储路径和校验和。 – 2012-04-25 21:54:47
@BalusC感谢百万:)这只是一个完美的答案。我刚刚得到了一个小小的最终怀疑。虽然检索我会得到二进制数据。因此,要将其转换为文件并显示该pdf文件,我该怎么办? – suraj 2012-04-26 04:25:10
使用'ResultSet#getBinaryStream()'将它从数据库中取回为'InputStream'。你想提供它作为下载?只需在一些适当的响应头文件中写入'HttpServletResponse#getOutputStream()',以便浏览器理解如何处理它。你想将它保存为文件吗?只需将它写入'新的FileOutputStream()'。等等。只需写入任何“OutputStream”即可。另请参阅http://stackoverflow.com/questions/4614935/how-to-display-a-pdf-file-in-jsp-using-servlet/4615155#4615155 – BalusC 2012-04-26 04:28:47