A simple file upload
In the following, a simple file upload will be shown. The example was built and tested with grails 0.4.2 but it will probably work in other versions as well, since there's nothing much special about it.
To build the file upload, you essentially have to do 3 things:
- Configure Spring
- Create the dialog for the user
- Handle the uploaded file
Spring configuration
In the spring configuration file at spring/resources.xml add the following piece of XML:
<bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize"><value>1000000</value></property>
</bean>
This will make the MultipartResolver available in grails.
Create the user dialog
In your gsp page add the following code for creating a form.
<g:form method="post" action="save" enctype="multipart/form-data">
<input type="file" name="file"/>
<input type="submit"/>
</g:form>
This will cause a file the was selected by the user to be submitted to the controller.
Handle the uploaded file
This is the part you put inside the controller. The following will parse a text file and print each line to the console.
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
[...]
def save = {
if (!(request instanceof MultipartHttpServletRequest)) {
println("no multipart")
}
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
CommonsMultipartFile file = (CommonsMultipartFile)multiRequest.getFile("file");
BufferedReader bin = new BufferedReader(new InputStreamReader(file.getInputStream()));
String line = bin.readLine();
// print each line
while (line != null) {
println("line: " + line);
line = bin.readLine();
}
}
This should be easily applicable for binary format, since once you have the InputStream you can handle the data as usual.

