我是Grails的新人。我试过几次上传文件。但失败了。我正在使用grails 2.3.11。在我的config.groovy文件中,我已经包含
grails.web.disable.multipart=true
我没有在BuildConfig中添加任何依赖文件上传。我需要它来解决问题。我在下面给出了代码
GSP代码:
<g:uploadForm action="upload" enctype="multipart/form-data" useToken="true">
<fieldset class="form">
<input type="file" name="file" />
</fieldset>
<fieldset class="buttons">
<g:submitButton name="upload" class="save" value="Upload" />
</fieldset>
</g:uploadForm>
我的控制器代码:
def file = request.getFile('file')
我也试过这段代码:
MultipartRequest multipartRequest = request as MultipartRequest
def file = multipartRequest.getFile('file')
if (file){
flash.message = "File found!!"
} else {
flash.message = "File NOT found. :-( "
}
redirect action:'list'
但每次我都遇到同样的错误:
groovy.lang.MissingMethodException: No signature of method:
org.apache.catalina.core.ApplicationHttpRequest.getFile()
is applicable for argument types: (java.lang.String) values: [file]
Possible solutions: getXML(), getPart(java.lang.String),
getAt(java.lang.String), getAt(java.lang.String), getLocale(), getInfo()
怎样才能解决这个问题?有没有完整的文件上传示例?
答案 0 :(得分:2)
您应该在config.groovy中设置grails.web.disable.multipart = false
。这意味着您要为服务器启用多部分请求。在你的控制器里面:
String content = request.getContentType()
if (content.contains("multipart/form-data") || (request instanceof MultipartHttpServletRequest)) {
MultipartFile uploadedFile = request.getFile('file')
if (!uploadedFile) {
flash.message = "No attachment found for upload!"
}else{
flash.message = "File uploaded successfully."
}
} else {
flash.message = "Unable to upload file, Bad Request!")
}