views:

655

answers:

1

I am trying to use the (flash based) YUI Uploader with a Java (Spring-based) back-end.

The typical way of uploading files in the Java Servlet world is to set the ENCTYPE='multipart/form-data' on the HTML form requesting the file from the user. With the right server side APIs (i.e. Commons FileUpload), it is possible to get the file on the server.

But I am stymied by how to achieve this with the YUI Uploader. I am able to reach the Java controller, and I am even able to extract the custom post values. But I have no idea how to extract the binary file data out of the request.

Has anyone out had any luck with a YUI uploader with a Java back-end?

+1  A: 

To answer my own question, and to make a long story short, this snippet of code did the trick:

@Controller
@RequestMapping("/FileUploadController")
public class FileUploadController {

    @RequestMapping(method = RequestMethod.POST)
    protected ModelAndView onSubmit(HttpServletRequest request) throws Exception{
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> /* FileItem */ items = upload.parseRequest(request);

        for (FileItem fileItem : items) {
            if (fileItem.isFormField()) {
//                processFormField(fileItem);
            } else {
                File uploadedFile = new File("/tmp/junk/" + fileItem.getName());
                fileItem.write(uploadedFile);
            }
        }
        return new ModelAndView("index");
    }
}

This example uses Spring, but you should be able to do exactly the same as long as you have HttpServletRequest object.

Julien Chastang