【问题标题】:Upload PDF to database and storage system (folder) in JSP在 JSP 中将 PDF 上传到数据库和存储系统(文件夹)
【发布时间】:2012-07-21 18:44:01
【问题描述】:

就像标题一样,我想问一下,如何将带有上传表单的 pdf 文件添加到我的存储文件夹(例如:uploadData),然后在 JSP 中将其作为文件添加到数据库中。

如果不行,可以作为文本添加到数据库中。

如果可以作为文件,该 pdf 的表格是什么类型的?斑点?还是文字?

我接受与我的问题相关的博客链接/其他链接

抱歉英语不好。

【问题讨论】:

    标签: java jsp pdf servlets file-upload


    【解决方案1】:

    Servlet 3.0 容器对多部分数据具有标准支持。它还支持写入本地文件系统。首先,您应该编写一个 HTML 页面,该页面接受文件输入以及其他输入参数。

    <form action="uploadservlet" method="post" enctype="multipart/form-data">
        <input type="text" name="name" />
        <input type="text" name="age" />
        <input type="file" name="photo" />
        <input type="submit" />
    </form>
    

    现在编写一个使用 Servlet 3.0 Upload API 的 UploadServlet。这是演示 API 用法的代码。首先,处理多部分数据的 servlet 应该使用以下两种方法中的任何一种来定义 MultiPartConfig:

    • Servlet 类上的@MultiPartConfig 注释
    • 在 web.xml 中,通过在定义中添加条目。

    这里是 UploadServlet,

    @MultipartConfig
    public class UploadServlet extends HttpServlet
    {
      protected void service(HttpServletRequest request, 
       HttpServletResponse responst) throws ServletException, IOException
      {
      Collection<Part> parts = request.getParts();
      if (parts.size() != 3) {
         //can write error page saying all details are not entered
       }
    
       Part filePart = httpServletRequest.getPart("photo");
       InputStream imageInputStream = filePart.getInputStream();
       //read imageInputStream
       filePart.write("somefiepath");
       //can also write the photo to local storage
    
       //Read Name, String Type 
       Part namePart = request.getPart("name");
       if(namePart.getSize() > 20){
           //write name cannot exceed 20 chars
       }
       //use nameInputStream if required        
       InputStream nameInputStream = namePart.getInputStream();
       //name , String type can also obtained using Request parameter 
       String nameParameter = request.getParameter("name");
    
       //Similialrly can read age properties
       Part agePart = request.getPart("age");
       int ageParameter = Integer.parseInt(request.getParameter("age"));
    
    
    
    }
    
    }
    

    如果您不使用 Sevlet 3.0 Container,您应该使用 Apache Commons File Upload。以下是使用 Apache Commons File Upload 的链接:

    参考资料:

    【讨论】:

      【解决方案2】:

      我所知道的处理文件上传的最简单方法是使用Commons FileUpload。 documentation 为您逐步概述了如何接受上传的文件,包括如何轻松地将它们复制到文件中。

      如果您决定将 PDF 放入数据库(我不会这样做),BLOB 是您的最佳选择,PDF 文件不是文本。

      不过,我建议不要将所有这些逻辑都塞进 JSP 中,而是塞进 servlet 中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-31
        • 1970-01-01
        • 1970-01-01
        • 2012-06-26
        相关资源
        最近更新 更多