user2259555
user2259555

Reputation: 233

Spring File upload and persisting object

I have a form which has two submit buttons. The save button will save an object to the database and at the same time save an upload file to a local directory. While the send button will generate an email automatically to a recipient.

What I have so far

    @RequestMapping(value = "/staff/setter/addPage", method = RequestMethod.POST)
public String processModule(@RequestParam("name") String name,
        @RequestParam("file") MultipartFile file, @ModelAttribute("module") 

      Module module, Staff staff, HttpServletRequest request, BindException errors,
      HttpSession session) {    

           if( request.getParameter("save") != null )
              {
     if(module != null){

         try {

             MultipartFile filea = module.getFileData();

             InputStream inputStream = null;
             OutputStream outputStream = null;
             if (filea.getSize() > 0) {
             inputStream = filea.getInputStream();
             outputStream = new FileOutputStream("C:\\Test\\"
             + filea.getOriginalFilename());
             System.out.println("==========Uploaded File 

                   Name=========");
             System.out.println(filea.getOriginalFilename());


                    System.out.println("====================================");
             int readBytes = 0;
             byte[] buffer = new byte[8192];
             while ((readBytes = inputStream.read(buffer, 0, 8192)) != 

              -1) {
             outputStream.write(buffer, 0, readBytes);
             }
             outputStream.close();
             inputStream.close();
             session.setAttribute("success", "File Uploaded 

           Successfully");
             session.setAttribute("uploadFile", "C:\\Test\\"
             + filea.getOriginalFilename());
             }
             } catch (Exception e) {
             e.printStackTrace();
             }


 //Save specific processing
     moduleService.save(module);
     }
     return "redirect:/staff/setter/addPage";   
 }

 else if( request.getParameter("send") != null )
 {
  //Send specific processing.
     SimpleMailMessage msg = new SimpleMailMessage(this.templateMessage);
     //msg.setTo(module.getCustomer().getEmailAddress());
     msg.setTo(module.getChecker().getEmail());
     //msg.setTo(staff.getChecker().getEmail());

     msg.setText(
         "Dear " + module.getChecker().getName()
         //"Dear " + staff.getChecker().getEmail()
             //+ module.getCustomer().getLastName()
             + "a coursework has been submitted for checking"
             + module.getModuleCode()
             +module.getModuleName());
     try{
         this.mailSender.send(msg);
     }
     catch(MailException ex) {
         // simply log it and go on...
         System.err.println(ex.getMessage());   

 }

 }
return "/staff/setter/view_submission";
}

So far the error is

      HTTP Status 400 - The request sent by the client was syntactically incorrect.

I would appreciate any help.

Edit: Jsp page

  <c:url var="processUrl" value="/staff/setter/addPage" />
 <form:form modelAttribute="module" method="POST" action="${processUrl}" name="module" 

  enctype="multipart/form-data">

   <form:hidden path="moduleId" />

    <div class="admin">
<table>

    <tr>

        <td class="module">

        </td>
        <td>Module Code:</td>

        <td>Module Name:</td>

    </tr>
    <tr>
    <td>Convenor:</td>
    <td>Checker:</td>

</tr>
<tr>
    <td>Weights:</td>
</tr>

  </table>
  </div>


<div class ="lecturer">
<h4>Lecturer Section</h4>
<ul>


<form:label path="fileName">Document Title:</form:label>
<form:input path="fileName" name="name"/><br/>

<form:label path="documentPath">Coursework Sample:</form:label>
<form:input path="documentPath" type="file" name="file" id="file"/><br/>

 <form:label path="liveDate">Live Date:</form:label>
<form:input path="liveDate"/><br/>

 <form:label path="submissionDate">Submission Date:</form:label>
 <form:input path="submissionDate"/><br/>

 <form:label path="filename">Marked Sample Title:</form:label>
  <form:input path="filename" id="file" name="name"/><br/>

 <form:label path="markedSamplePath">Marked Sample:</form:label>
 <form:input path="markedSamplePath" type="file" name="file"/><br/>

 </ul>

</div>

 </form:form>

Upvotes: 0

Views: 197

Answers (1)

Martin Frey
Martin Frey

Reputation: 10075

If you like to avoid the hassle of handling multipart forms and possibly give the user a nicer experience. For example your form data has an error and the user needs to resubmit the form your fileupload would be lost.

I use fineuploader to build an uploadedfilequeue as hidden inputs and the uploads themself are seperate requests.

Explained here: Preserving value for <form:input type="file"> with Spring MVC

Upvotes: 1

Related Questions