views:

39

answers:

1

What is the best way to upload a directory in grails ?

I try this code :

  def upload = {
    if(request.method == 'POST') {
        Iterator itr = request.getFileNames();

        while(itr.hasNext()) {
            MultipartFile file = request.getFile(itr.next());
            File destination = new File(file.getOriginalFilename())

            if (!file.isEmpty()) {
                file.transferTo(destination)
                // success
            }
            else
            {
                // failure
            }
        }

        response.sendError(200,'Done');
    }
  }

Unfortunately, I can only upload file by file. I would like to define my directory, and upload all files directly.

Any ideas ?

+1  A: 

There is one major misconception here. The code which you posted will only work if both the server and the client runs at physically the same machine (which won't occur in real world) and if you're using the MSIE browser which has the misbehaviour to send the full path along the filename.

You should in fact get the contents of the uploaded file as an InputStream and write it to any OutputStream the usual Java IO way. The filename can be used to create a file with the same name at the server side, but you'll ensure that you strip the incorrectly by MSIE sent path from the filename.

As to your actual functional requirement, HTML doesn't provide facilities to upload complete directories or multiple files by a single <input type="file"> element. You'll need to create a client application which is capable of this and serve this from your webpage, like a Java Applet using Swing JFileChooser. There exist 3rd party solutions for this, like JumpLoader.

BalusC
Ok, I can't upload complete directories via HTML.JumpLoader look nice, but not free (I will try to find similar projects). Thanks !
Fabien Barbier
It is free. Read once again, you only need to pay whenever you want a logo-less version or a full open source version. Click the *Download* link in top nav bar to get the free version.
BalusC