Jun 14 2008
Uploading files to a groovlet
Groovlets, could be the coolest thing since sliced-bread … except for the fact that it does n’t seem to support fileupload! what? why? is there a solution?
Yes!
After some initial research this didn’t seem as an easy thing to do.
This patch suggested changing code in groovy itself, which is something I am not inclined to do. So, I used the ideas from that patch and made the fileupload (multipart) work without it …
I downloaded the commons-fileupload-1.2.1.jar commons-io-1.4.jar from Apache commons project
into jetty-6.1.11/webapps/glet/WEB-INF/lib/
Then added the needed code to the beginning of the menu.groovy (renamed .glet to work with my web.xml)
import org.apache.commons.fileupload.DiskFileUpload import org.apache.commons.fileupload.FileItem import org.apache.commons.fileupload.FileUpload import org.apache.commons.fileupload.FileUploadException import java.util.HashMap; import java.util.List; import java.util.Map; Map uploads = new HashMap(); if(FileUpload.isMultipartContent(request)) { DiskFileUpload parser = new DiskFileUpload(); List items; try { items = parser.parseRequest(request); } catch (FileUploadException e) { //Ooops! Something gone bad while parsing request. throw new RuntimeException(e); } int i = 0 int n = items.size() for( i = 0; i < n; i++) { FileItem item = (FileItem) items.get(i); String itemName = item.getFieldName(); if(item.isFormField()) { params.put(itemName, item.getString()); } else { uploads.put(itemName, item); } } } def mealType = params['mealType'] def menuFile = uploads['menuFile'] html.html { head { title("Gromit Menu") } body { table { tr { td { span("This is your menu for gromit for ${mealType}") br() i("You uploaded file ${menuFile.name}, ${menuFile.size} bytes") } } tr { td { menuFile.inputStream.eachLine { html.span(it) html.br() } } } } } }
Conclusion
Groovy is not just a wonderful new agile programming language, its much more than that. As it builds its success on the shoulders of giants (Java et al), the sky is the limit for any problem you might come across.