如何使用servlet将pdf文件存储在postgresql数据库中? [英] How to store a pdf file in postgresql database using servlets?

查看:191
本文介绍了如何使用servlet将pdf文件存储在postgresql数据库中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < center>< form action =pdf方法=postenctype =multipart / form-data> 
< b>上传证书< / b>
< input type =filename =file/>< / center>
< center> < input type =submit/>< / center>
< / form>

提交表单时,将调用pdf Servlet。在servlet内部,请求对象被解析,使用InputStream读取文件(pdf),如下面的代码所示:

  protected void doPost (HttpServletRequest paramHttpServletRequest,HttpServletResponse paramHttpServletResponse)
throws ServletException,IOException
{
尝试
{
List localList = new ServFileItemFactory()).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();
尝试
{
PdfReader localPdfReader = new PdfReader(localInputStream);
paramHttpServletResponse.sendRedirect(takedetails.jsp);

catch(InvalidPdfException localInvalidPdfException)
{
paramHttpServletResponse.sendRedirect(upload.jsp);




catch(FileUploadException localFileUploadException)
{
throw new ServletException(Can not parse multipart request 。,localFileUploadException);






$ b您可以看到,我使用InputStream对象来检查为文件格式为PDF。


现在我想把这个pdf文件保存到postgresql数据库。我应该在postgresql中使用哪个字段,以及如何从InputStream对象中获取文件以将其存储在数据库中?

目前还不清楚你正在使用什么持久性API。 JDBC? JPA?好醇'冬眠?我将假设JDBC。在JDBC中,您可以使用 PreparedStatement#setBinaryStream() 在数据库中存储 InputStream PreparedStatement#setBytes() 在数据库中存储 byte [] 。无论哪种方式,在PostgreSQL中,你需要一个 bytea <
$ b

当你通过 PdfReader InputStream 是不合适的。它可以只读一次。每当您需要再次读取 InputStream 时,客户端不会多次重新发送文件。您需要首先将 InputStream 复制到 byte [] 中。

  ByteArrayOutputStream output = new ByteArrayOutputStream(); 
IOUtils.copy(localFileItem.getInputStream(),output);
byte [] filecontent = output.toByteArray();

IOUtils 是Apache Commons IO;如果你正在使用FileUpload,那么你已经拥有了它)



不要忘记把iText改成使用 byte [] 代替:

  PdfReader localPdfReader = new PdfReader(filecontent); 

当您通过iText验证后,您可以将其存储在PostgreSQL bytea 使用JDBC的列如下:

  statement = connection.prepareStatement(INSERT INTO files名称,内容)VALUES(?,?)); 
statement.setString(1,filename);
statement.setBytes(2,filecontent);
statement.executeUpdate();


I am uploading a file from HTML

 <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>

On submitting the form, pdf Servlet is called. Inside the servlet the request object is parsed and file(pdf) is read using InputStream as given in code below.

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

As you can see,I used InputStream object to check for file format as pdf.

Now I want to save this pdf file to postgresql Database. What field should i use in postgresql and how can I get the file from InputStream object to store it in database?

解决方案

It's unclear what persistence API you're using. JDBC? JPA? Good ol' Hibernate? I'll assume JDBC. In JDBC, you can use PreparedStatement#setBinaryStream() to store an InputStream in the database, or PreparedStatement#setBytes() to store a byte[] in the database. Either way, in PostgreSQL you need a bytea column for this.

As you're verifying the uploaded file by a PdfReader first, the InputStream is unsuitable. It can namely be read only once. The client ain't going to resend the file multiple times each time you need to read the InputStream again. You need to copy the InputStream to a byte[] first.

ByteArrayOutputStream output = new ByteArrayOutputStream();
IOUtils.copy(localFileItem.getInputStream(), output);
byte[] filecontent = output.toByteArray();

(IOUtils is part of Apache Commons IO; if you're using FileUpload, then you already have it)

Don't forget to change iText to use the byte[] instead:

PdfReader localPdfReader = new PdfReader(filecontent);

After you've validated it by iText, you can store it in a PostgreSQL bytea column using JDBC as follows:

statement = connection.prepareStatement("INSERT INTO files (name, content) VALUES (?, ?)");
statement.setString(1, filename);
statement.setBytes(2, filecontent);
statement.executeUpdate();

这篇关于如何使用servlet将pdf文件存储在postgresql数据库中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆