0

I have a httpservlet on GAE which handles a form. The form has an button. In the servlet I use apache.commons.fileupload to handle single file uploads, butI have no idea how to handle multiple file array...any help appreciated.

Form:

<form id="fileupload" action="/Save" method="Post" enctype="multipart/form-data">
    <input name="title" type=text />
    <textarea name="info"></textarea>
    <input type="file" name="files[]" multiple>
    <input id="save" type="submit" value="Save this">
</form>

Servlet:

FileItemIterator iter = upload.getItemIterator(req);
while (iter.hasNext()) {
    FileItemStream item = iter.next();
    String name = item.getFieldName();
    InputStream stream = item.openStream();
    if (item.isFormField()) {
        System.out.println("Form field " + name + " with value "
            + Streams.asString(stream) + " detected.");
    } else {
        // name here will be "files[]"
        System.out.println("File field " + name + " with file name "
        + item.getName() + " detected."); 
        //MY NONWORKING ATTEMPT AT HANDLING THE FILES[] ARRAY: <- this is my question, how to do this?
        Object files[] = Streams.copy(stream);
        for(int i = 0; i < files.size(); i++){
            String fileType = files[i].getContentType();
            Blob imageBlob = new Blob(Files[i]);
        }
    }
}

1 Answers1

0

You are trying to get all files from one FileItemStream, while actually each FileItemStream is it's own file.

// INSERT THIS INSTEAD OF YOUR NONWORKING PART
String filename = item.getName();
String contentType = item.getContentType();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) 
    // here save the buffer to blobstore
}

For saving data to blobstore see how to use new Files API to save into blobstore.

Peter Knego
  • 79,991
  • 11
  • 123
  • 154