Uploading a file
The following is a simple example of a file upload in Grails. This example was built and tested with Grails 1.0.2.
Create the form in the view
In your GSP page, add the following code for creating a form for uploading the file.
<g:form method="post" action="save" enctype="multipart/form-data"> <input type="file" name="file"/> <input type="submit"/> </g:form>
Handle the upload in the controller
Here is a controller action that prints the entire text file to the console. The request object is automatically a Spring MultipartHttpServletRequest when dealing with a multipart HTTP request.
def save = {
println request.getFile("file").inputStream.text
}
Labels
(None)
Comments (3)
Mar 08, 2007
Graeme Rocher says:
You do know that Grails already configures CommonsMultipartResolver and that it ...You do know that Grails already configures CommonsMultipartResolver and that it has special features for dealing with file uploads? See: http://grails.org/Controllers
Mar 25, 2007
Marius says:
It doesn't work for me. I'm using Grails 0.5, Groovy 1.0, Java 1.5.011: Message:...It doesn't work for me. I'm using Grails 0.5, Groovy 1.0, Java 1.5.0_11:
Message: No signature of method: org.codehaus.groovy.grails.web.servlet.GrailsHttpServletRequest.getFile() is applicable for argument types: (java.lang.String) values:
*Caused by:*groovy.lang.MissingMethodException: No signature of method: org.codehaus.groovy.grails.web.servlet.GrailsHttpServletRequest.getFile() is applicable for argument types: (java.lang.String) values:
Class: CompanyController
At Line: [87]
Code Snippet:
87: CommonsMultipartFile file = (CommonsMultipartFile)multiRequest.getFile("file");
88: BufferedReader bin = new BufferedReader(new InputStreamReader(file.getInputStream()));
Mar 25, 2007
Marius says:
Solved. It was my mistake, I was going in action save before submitting the form...Solved. It was my mistake, I was going in action save before submitting the form, so I suppose there was no file.