I am having a helluva time with multipart upload in Grails. Most sources point to that being very simple, and no additional configuration required. Yet that approach was giving me a null object on uploaded file.
Here is the exception i get:
ERROR errors.GrailsExceptionResolver - Cannot get property 'originalFilename' on null object
java.lang.NullPointerException: Cannot get property 'originalFilename' on null object
I fiddled with adding Spring configuration to the resources.groovy:
beans = {
multipartResolver(org.springframework.web.multipart.commons.CommonsMultipartResolver){
maxInMemorySize=10240
maxUploadSize=10000000
}
}
And attempted to do the same in the WEB-INF/applicationContext.xml:
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"/>
</bean >
Here the .gsp form code:
<g:form action="rawUpload" method="POST" name="uploadImageForm" enctype="multipart/form-data">
<tr><td colspan="2" align="right"><div id="showImg" align="center"> </div></td>
<td colspan="2" align="right">
<input type="file" name="Image" />
</td></tr>
<tr><td colspan="4">
<div class="button" align="right">
<button type="submit" id="ImageBtn" name="ImageBtn" value="Upload Image" >Upload Image</button>
</div>
</td></tr>
</g:form>
And in the controller:
//import org.springframework.web.multipart.MultipartHttpServletRequest;
//import org.springframework.web.multipart.commons.CommonsMultipartFile;
def rawUpload = {
//Spring MultipartHttpSevletRequest
//MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
//CommonsMultipartFile uploadedFile = (CommonsMultipartFile) mpr.getFile("reviewImage");
//fileUploadCommand uploadedFile = new fileUploadCommand(params.reviewImg)
log.debug "ImageController: request params are $params"
def uploadedFile = request.getFile('reviewImg')
if (!uploadedFile?.empty){
//println "Class: ${uploadedFile.class}"
//println "Name: ${uploadedFile.name}"
//println "OriginalFileName: ${uploadedFile.originalFilename}"
//println "Size: ${uploadedFile.size}"
//println "ContentType: ${uploadedFile.contentType}"
def webRootDir = servletContext.getRealPath("/")
def reviewDir = new File(webRootDir, "/images_app/${session.user.login}")
reviewDir.mkdirs()
uploadedFile.transferTo( new File( reviewDir, uploadedFile.originalFilename))
}
}