Wednesday, December 8, 2010

File Upload with Uplodify and Spring MVC

It provides user better experience if you can provide a progress indicator when they upload file to server. But this leave you not too many choices but flash in the client. Here is a quick note when I use Uplodify , a jQuery plugin that employ flash to upload file to the server powered by Spring MVC.

Client Side


1. include necessary library
<script type="text/javascript" src="<c:url value='/scripts/jquery-1.4.4.min.js'/>"></script>
<link href="<c:url value='/components/uploadify/uploadify.css'/>" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="<c:url value='/components/uploadify/swfobject.js'/>"></script>
<script type="text/javascript" src="<c:url value='/components/uploadify/jquery.uploadify.v2.1.4.min.js'/>"></script>


2. leave a place holder for the input field
<input id="file_upload" name="file" type="file" />
You don't have to create a form for this filed. uplodify will take care of it for you.

3. initialize uploadify
$('#file_upload').uploadify({
   
       'uploader'  : '',
       'multi': false,
  
       'script'    : 'http://localhost:8080/myapp/file/upload/;jessionid=${pageContext.session.id}',
       'scriptData'  : {},
  
       'cancelImg' : '', 
       
       'sizeLimit'   : 5000000,
       'removeCompleted' : true,
       'auto'      : true,
      
      'fileDataName' : 'file',
       'onComplete' : function(event,ID,fileObj,response,data) {
      
        }

  
     });

1. I add sessionid in script, so in your server side you can get it since uploadify is flash, it won't keep sessionid.

2. 'fileDataName' : 'file', This parameter is very important, it must be matched with your Spring MVC Controller's parameter name, in my case, is @RequestParam MultipartFile file. Otherwise, you will get an MissingServletRequestParameterException, "Required MultifartFile parameter 'file' is not present.

Server Side


4. add apache's commons-fileupload dependency
<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.2.1</version>
  </dependency>

5. decalare multipartResolver in your dispatch-serverlet.xml
<bean id="multipartResolver"
  class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

6. Create FileUploadController
@Controller
@RequestMapping("/file")
public class FileUploadController {
 private static Log log = LogFactory.getLog(FileUploadController.class);
 @Autowired
 protected UploadService uploadService;

 @RequestMapping(value = "upload", method = RequestMethod.POST)
 public String processUpload(@RequestParam MultipartFile file,
   ModelMap modelMap, HttpServletRequest request) throws Exception {

  log.debug("========= upload file:" + file.getOriginalFilename());
                 //you can do something with the uploaded file
  //UploadedFile uploaded = uploadService.save(file);

  modelMap.addAttribute("file", uploaded);

  return "file";
 }
}

2 comments:

vamsee said...

Ke Cai

thanks for your tutorial. i always get the error and the file is never transfered to the spring controller. great if you could shed some light on the multiple file upload.

Thanks,
Vamsee

Nemanja said...

@vamsee
I am facing the same problem. Maybe you should put Spring on DEBUG level and see what the problem is.

My problem is with spring security. I tried this solution, but my request is redirected to login page (because HttpSession is null). Do you have some proposition how to solve this problem,

Best regards,
Nemanja