Saturday, March 16, 2013

HTML5 multiple upload with Spring

HTML5 allows for multiple file uploading so for those Browsers supporting it you do not need flash any longer (swfUpload flash plugin has been the defacto way for uploading multiple documents for years). In its more primitive way this would be the form you would use:
Then this is the Spring code needed in the backend (Controller method). In the below code we add an error with an unresolvable key from message properties (the name of the file).
    public ModelAndView multipleUpload(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "files", required = false) MultipartFile[] files, @ModelAttribute("document") Document document,
        BindingResult result) {
        ControllerContext ctx = new ControllerContext(request, response);

        if (!isValidCsrfToken(ctx)) {
            return getModelAndView(ctx, SHOW_PATH, result);

        for (MultipartFile multipartFile : files) {
            try {
            } catch (Exception e) {
                String errorMessage = e.toString();
                result.reject(multipartFile.getOriginalFilename(), errorMessage);

        return getModelAndView(ctx, SHOW_PATH, result);
As a side note if the expected response type is JSON we expose the BindingResult as a Map where for each file name we inform exactly what the problem is. The BindingResult object cannot be serialized via JACKSON as far as I can tell so for JSON responses we cannot take advantage of binding as we do with direct JSP HTML rendering.

No comments: