管理多个上传文件到mysql db

时间:2014-11-19 07:14:11

标签: java mysql hibernate jsp spring-mvc

我的问题与多文件上传有关。我使用Viral Patel example作为参考,并且能够将任何类型的文件上传到db,它正在非常好地存储和检索。和文件作为blob类型存储在mysql db中。现在我的要求是上传不是一个文件,而是上传多个文件。我使用javascript添加了一个按钮来添加更多文件。它工作正常。但如果我添加2或3个文件,则没有动态创建列。请建议我。下面是我的代码

这是我的POJO课程:

   **POJO CLASS**

   @Entity
   @Table(name="AGREEMENT") 
   public class Agreement implements Serializable{

    private static final long serialVersionUID = 2641L;


   @Id
     @Column(name="AGREEMENT_ID")
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int agreementId;


    @ManyToOne
    @JoinColumn(name="CUSTOMER_ID")
     private Customer customer;

     @Column(name="CONTENT")
     @Lob
     private Blob content;


     @Column(name="filename")
      private String filename;

     @Column(name="content_type")
     private String contentType;

   //getters and setters
      }

这是控制器:

   **Controller**
      @RequestMapping(value="/agreement.htm", method=RequestMethod.GET)
         public ModelAndView agreementForm(ModelMap model,HttpServletRequest request, 
      Agreement agreement) {
            int customerId=Integer.parseInt(request.getParameter("id"));
            logger.info("Agreememt to be added" +customerId);
            Customer customer = new Customer(customerId);
            agreement.setCustomer(customer);
            model.addAttribute("agreement", agreement);
            ModelAndView mav = new ModelAndView("addAgreement");
            return mav;
    }

     @RequestMapping(value = "/addAgreement.htm", method = RequestMethod.POST)

     public String queryAddConfirm(@ModelAttribute Agreement  
      agreement,@RequestParam("file") MultipartFile file, BindingResult result, ModelMap 
      model, HttpServletRequest servlet, HttpSession session) throws Exception
    {       

    Long fileSize = file.getSize();

    Blob blob = Hibernate.getLobCreator(sessionFactory.openSession()).
     createBlob(file.getInputStream(), fileSize);

      logger.info("Added Agreements");
        //query.setContent(content);
        agreement.setContent(blob);
        agreement.setContentType(file.getContentType());
        agreement.setFilename(file.getOriginalFilename().toString());



      model.addAttribute("agreement", agreement);
      model.addAttribute("agreement", agreement.getCustomer());

      System.out.println("customerID"+agreement.getCustomer());
      customerService.addAgreements(agreement);

    return "redirect:/customerAdmin/adminListAgreement.htm";
    }
     @RequestMapping("/download/{agreementId}")
        public String download(@PathVariable("agreementId")
                Integer agreementId, HttpServletResponse response) {


           Agreement agreement = customerService.fileDownload(agreementId);
            try {
                response.setHeader("Content-Disposition", "inline;filename=\"" 
                    +agreement.getFilename().toString()+ "\"");


                OutputStream out = response.getOutputStream();
                response.setContentType(agreement.getContentType().toString());
                IOUtils.copy(agreement.getContent().getBinaryStream(), out);


                out.flush();
                out.close();

            } catch (IOException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }


            return null;
            }

这是Dao实施层:

      **Customer DaoIMPL**
          public void addAgreements(Agreement agreement) {

           getCurrentSession().save(agreement); 
                }

这是添加文件jsp。在这里我创建了一个名为“添加文件”的按钮。当我单击添加按钮时,新的浏览按钮正在创建,并且能够选择文件。但是在db中,动态提交后没有创建行。请帮助我如何添加动态列以及如何下载(检索)它。

      **addAgreement JSP**

      <div id=add-container align="center" style="height:400px;width:400px"><br>
                        <p><font color="white" size="6px" face="Comic sans MS" >Add 
        Agreement</font></p><hr>


            <div class="containerdiv" align="center">


                    <form:label path="customer" type="text" align="left" value="" 
             maxlength="50">Customer ID :<span class="error"></span></form:label>
                    <form:input style="width:300px" path="customer" readonly="true"/>
                    <font color="red"><form:errors path="customer" /></font></div><br>


        <p>Select files to upload. Press Add button to add more file inputs.</p> 


    <input id="addFile" type="button" value="Add File" />

      <div class="containerdiv" align="center">
          <table id="fileTable" align="center">
    <tr>
        <td><input name="file" id= "file" type="file" /></td>
    </tr>


         </table></div>
        <br>
          <div class="row" Align="center" margin-top: "15px;">
                        <input  class="submit" style="width:150px" type="submit"  
             value="upload" class="large-centered radius button columns"/>


                        <input class="cancel" style="width:150px" type="button" 
         value="Cancel" class="large-centered columns button disabled radius closeButton" 
          onclick=" goBack()"/>
                    </div>    


                </div>

控制器显示添加的文件列表

           **listAgreement GET(controller)**


           @RequestMapping(value="/adminListAgreement.htm", method=RequestMethod.GET)
        public String AgreementList(ModelMap model) {
            logger.info("Admin List Agreement GET");
            List<Agreement> agreement = customerService.findAllAgreements();
            model.addAttribute("agreement", agreement);
            return "adminListAgreement";
    }

这是adeed jsp文件列表

         **listAgreement JSP**

    <tr>  

                            <td class="heading">Agreement Id</td>
                            <td class="heading">Content</td>
                            <td class="heading">File Name</td>
                            <td class="heading">CustomerID</td>

                        </tr>
                </thead>
                <tbody>
                    <c:forEach items="${agreement}" var="agreement" >
                        <tr>
                            <td>${agreement.agreementId}</td> 
                              <td>
                               <a href="${pageContext.request.contextPath}/customerAdmin 
                 /download/${agreement.agreementId}.htm">
                               <img src="${pageContext.request.contextPath}/resources/images
              /download1.jpg" 
                               border="0"
                                title="Download this document"/></a> 
                             </td>  
                               <td> ${agreement.filename}</td> 

                               <td>${agreement.customer}</td> 
                            <%--  <td>${query.image}</td> --%>

                        </tr>
                    </c:forEach>
                </tbody>


      <script>
      $(document).ready(function() {
         //add more file components if Add is clicked
            $('#addFile').click(function() {
       var fileIndex = $('#fileTable tr').children().length - 1;
        $('#fileTable').append(
            '<tr><td>'+
            '   <input type="file" name="files['+ fileIndex +']" />'+
            '</td></tr>'
            );
       });

     });
     </script>

1 个答案:

答案 0 :(得分:0)

我通过将10个浏览按钮添加到10个文件而不是使用自动添加按钮来添加不同的下载路径来解决它。我刚刚添加了十列和十个浏览按钮,并保留了不同的下载路径来下载它。:)