Couldn't upload file at any cost in grails - grails

I am new in Grails. I tried for several times to upload a file. But failed. I am using grails 2.3.11 . And In my config.groovy file, I already include
grails.web.disable.multipart=true
I didn't add any dependency in BuildConfig for file uploading. I need it to solve badly. I am giving Code in below
GSP code :
<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>
My Controller code:
def file = request.getFile('file')
I also tried with this piece of code :
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'
But each and everytime I got the same error :
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()
How can solve this problem? Is there any complete example of file uploading?

You should set grails.web.disable.multipart = false inside config.groovy. This means that you want to enable multipart requests to your server. And inside your controller:
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!")
}

Related

HTML5 drag and drop multi-file upload grails plugin

i'm using HTML5 drag and drop multi-file upload plugin, to upload some files in my Grails application , but i want to save the uploaded files to DB but i don't know what is the object that is holding the uploaded files i searched in request and params , here is my the tag in the _form view:
<uploadr:add name="myUploadrName" controller="photos" action="save" direction="up" maxVisible="8" unsupported="/my/controller/action" rating="false" voting="false" colorPicker="false" maxSize="204800" />
here is the create view :
<g:form url="[resource:photosInstance]" enctype="multipart/form-data"><fieldset class="form">
<g:render template="form"/>
</fieldset>
<fieldset class="buttons">
<g:submitButton id = "submitBtn" name="create" class="save" value="${message(code: 'default.button.create.label', default: 'Create')}" />
</fieldset>
</g:form>
here is the save action :
def save(Photos photosInstance) {
if (photosInstance == null) {
notFound()
return
}
if (photosInstance.hasErrors()) {
respond photosInstance.errors, view:'create'
return
}
request.getFileNames().each{
request.getFiles(it).each { file ->
// loop through all files selected
println "name: $file.name Originalfilename: $file.originalFilename contentType: $file.contentType"
photosInstance= new Photos(photo:file.bytes).save(failOnError:true)
}
}
/*request.withFormat {
form multipartForm {
flash.message = message(code: 'default.created.message', args: [
message(code: 'photos.label', default: 'Photos'),
photosInstance.id
])
redirect photosInstance
}
'*' { respond photosInstance, [status: CREATED] }
}*/
}
A little hard to help when I don't have the controller code, but try this:
UploadedFile uploadedFile = UploadedFile.get(params.fileId)
if (!uploadedFile) response.sendError(404, "No uploaded file could be found matching id: ${params.fileId}.")
GridFSFile gridFSFile = uploadedFile.file
if (!gridFSFile) response.sendError(404, "No file attached to UploadedFile")

how to upload file into server directory with grails?

how to upload file into server directory..
if my project at D:\myapp and i run with cmd d:\myapp grails run-app
when i run this app and other Computer run it and upload file..it will save ini computer server in directory D:\myapp\upload ?
i try this ini gsp.
<g:form action="list" enctype="multipart/form-data" useToken="true">
<span class="button">
<input type="file" name="filecsv"/>
<input type="button" class="upload" value="Upload"
onclick='location.href = "${createLink(url: [action: 'upload'])}"'/>
</span>
</g:form>
def upload = {
def f = request.getFile('filecsv')
if (f.empty) {
flash.message = 'file cannot be empty'
render(view: 'list')
return
}
f.transferTo(new File('C:\Users\meta\Documents\workspace-sts-2.5.2.RELEASE\wawet\wallet\uploads\file_name.csv'))
response.sendError(200, 'Done')
}
this is the error :
2014-02-03 10:43:02,706 [http-8080-2] ERROR errors.GrailsExceptionResolver - No signature of method: org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getFile() is applicable for argument types: (java.lang.String) values: [filecsv]
Possible solutions: getXML(), getAt(java.lang.String), getAt(java.lang.String), getLocale(), getJSON(), getHeader(java.lang.String)
groovy.lang.MissingMethodException: No signature of method: org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getFile() is applicable for argument types: (java.lang.String) values: [filecsv]
Possible solutions: getXML(), getAt(java.lang.String), getAt(java.lang.String), getLocale(), getJSON(), getHeader(java.lang.String)
at com.teravin.wallet.LoanAccountController$_closure12.doCall(com.teravin.wallet.LoanAccountController:308)
at com.teravin.wallet.LoanAccountController$_closure12.doCall(com.teravin.wallet.LoanAccountController)
at java.lang.Thread.run(Thread.java:744)
The destination is only a file like in Java.
def f = request.getFile('some_file')
//validate file or do something crazy hehehe
//now transfer file
File fileDest = new File("Path to some destination and file name")
f.transferTo(fileDest)
OR if you want to store it at some path relative to user home:
def homeDir = new File(System.getProperty("user.home")) //user home e.g /home/username for unix
File fileDest = new File(homeDir,"path/to/some_folder")
f.transferTo(fileDest)
UPDATE
As per why your getFile is not working, you are not submitting your form:
<g:form action="list" enctype="multipart/form-data" useToken="true">
<span class="button">
<input type="file" name="filecsv"/>
<input type="button" class="upload"
value="Upload"
onclick='location.href = "${createLink(url: [action: 'upload'])}"'/>
</span>
</g:form>
Should be:
<g:form action="upload" enctype="multipart/form-data" useToken="true">
<span class="button">
<input type="file" name="filecsv"/>
<input type="submit" class="upload" value="upload"/>
</span>
</g:form>
if you need to use javascript you should submit the form instead of adding a link to another page.
The location of your Grails app doesn't matter. You have to specify the full destination path in your controller. Here is an example
def upload() {
def f = request.getFile('filecsv')
if (f.empty) {
flash.message = 'file cannot be empty'
render(view: 'uploadForm')
return
}
f.transferTo(new File('D:\myapp\upload\file_name.txt'))
response.sendError(200, 'Done')
}
final String IMAGE_DIR = "${servletContext.getRealPath('/images')}/";
def employeeId = "dablu_photo";
def employeePicture = request.getFile("cv_");
String photoUrl ="";
if (employeePicture && !employeePicture.empty) {
if (new java.io.File(IMAGE_DIR+"/employee_photo/"+employeeId+".png")?.exists()){
FileUtils.deleteQuietly(new java.io.File(IMAGE_DIR+"/employee_photo/"+employeeId+".png"));
}
employeePicture.transferTo(new java.io.File(IMAGE_DIR+"/employee_photo/"+employeeId+".png"))
}

Why can't I find my uploaded file in Grails

I am still new to Grails. I have an app that has a file upload. I have added this to the controller
def upload = {
def f = request.getFile('myFile')
if(!f.empty) {
f.transferTo( new File("${f.name}") )
response.sendError(200,'Done');
} else {
flash.message = 'file cannot be empty'
render(view:'uploadForm')
}
}
and this is in _forms.gsp
<div class="fieldcontain ${hasErrors(bean: reportInstance, field: 'myFile', 'error')} ">
<label for="myFile">
<g:uploadForm action="upload">
<input type="file" name="myFile"/>
<input type= "submit" value="Upload"/>
</g:uploadForm>
</label>
When I use a g:link to try to retrieve the upload I get redirected and there is nothing displayed
Any advice would be greatly appreciated
g:link I am using
<g:link controller ="Report"
action="listByUserCompany"
>Show first ten ordered by Title</g:link>
class UploadController {
def index() { }
def fileupload () {
def f = request.getFile('myFile')
if(!f.empty) {
f.transferTo( new File("${f.name}") )
render(view:'upload')
}
else {
flash.message = 'file cannot be empty'
render(view:'upload')
}
}
}
<body>
<g:uploadForm name="myUpload" action="fileupload" controller="upload">
<input type="file" name="myFile" />
<input type= "submit" value="Upload"/>
</g:uploadForm>
</body>
i used the above code in my controller and gsp and i made a view named upload in view->upload->upload.gsp .My file uploaded success fully in the root directory of the project itself with name myfile

update user image in directory in grails

I have each user's image in my project directory like user1.jpeg, user2.jpeg and so on. But when I try to change a user image it is throughing a error. I am not understanding what to do. Here is the error as follows >>>
Cannot cast object 'org.apache.catalina.core.ApplicationHttpRequest#21740230' with class 'org.apache.catalina.core.ApplicationHttpRequest' to class 'org.springframework.web.multipart.MultipartHttpServletRequest'
And here is my update action >>>
def updateUser = {
String message = ""
MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
CommonsMultipartFile f = (CommonsMultipartFile) mpr.getFile("userPhoto")//getFile("userPhoto");
if(!f.empty) {
def user = User.get(1)
user.avatarType = f.getContentType()
if(user.save()){
def userId = user.id
String username = user.username
println(userId)
String fileName = username + "." + f.getContentType().substring(6)
new File( grailsApplication.config.images.location.toString() ).mkdirs()
f.transferTo( new File( grailsApplication.config.images.location.toString() + File.separatorChar + fileName) )
message = "Here is your updated Information >>> "
render(view: 'userInfo', model: [message: message],)
}else{
message = "Can not Update User !!!"
render(view: 'editUser', model:[message: message])
return;
}
}else {
flash.message = 'file cannot be empty'
}
}
Can anyone please help me on this please? I am using grails 2.1.0.
EDIT ::
and here is the view for edit user >>>
<div class="main">
<g:form controller="user" action="updateUser">
User Name : ${username} <br/>
Photo : <input type="file" name="userPhoto" /> <p></p>
<g:hiddenField name="userId" id="userId" value="${userId}"/>
<g:submitButton name="updateUser" value="Update" />
</g:form>
// MultipartHttpServletRequest mpr = (MultipartHttpServletRequest)request;
def f = request.getFile("userPhoto")//getFile("userPhoto");
I have to use <g:uploadForm /> see http://grails.org/doc/latest/guide/theWebLayer.html#uploadingFiles
Everything is fine in your code just add enctype="multipart/form-data" in the form tag, like
<g:form controller="user" action="updateUser" enctype="multipart/form-data">
...
</g:form>
and your code works.

uploading a file in grails

I am trying to upload a file in grails in my gsp I have:
<g:form id="update" url="[action: 'updateStatus',]">
<g:textArea name="message" value="" cols="3" rows="1"/><br/>
<g:textField id="tagField" name="tag" value=""/><br/>
<input id="inputField" type="file" name="myFile" enctype="multipart/form-data" />
<g:submitButton name="Update Status"/>
</g:form>
In my controller i have:
def updateStatus(String message) {
if (params.myFile){
def f = request.getFile('myFile')
}
The request get file is failing with this error:
No signature of method: org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestWrapper.getFile() is applicable for argument types: (java.lang.String) values: [myFile]
Any ideas why this is as I have and are using getFile in my other controllers which works fine.
here is working file submit:
the form (gsp)
<form method="post" enctype="multipart/form-data">
<p><input type='file' name="cfile"/></p>
<input type='submit'>
</form>
the controller that will store submitted file into 'D:/submitted_file':
def index() {
if(params.cfile){
if(params.cfile instanceof org.springframework.web.multipart.commons.CommonsMultipartFile){
new FileOutputStream('d:/submitted_file').leftShift( params.cfile.getInputStream() );
//params.cfile.transferTo(new File('D:/submitted_file'));
}else{
log.error("wrong attachment type [${cfile.getClass()}]");
}
}
}
this works for me (grails 2.0.4)
You need enctype="multipart/form-data" on the g:form tag to make the browser use a multipart request.
In order to upload a file you must set the enctype on the form. To do so you can make use of the <g:uploadForm> which is identical to the standard form tag except that it sets the enctype attribute to "multipart/form-data" automatically.
I prefer to make use of the Grails Selfie Plugin an Image / File Upload Plugin to attach files to your domain models, upload to a CDN, validate content, or produce thumbnails.
Domain
import com.bertramlabs.plugins.selfie.Attachment
class Book {
String name
Attachment photo
static attachmentOptions = [
photo: [
styles: [
thumb: [width: 50, height: 50, mode: 'fit'],
medium: [width: 250, height: 250, mode: 'scale']
]
]
]
static embedded = ['photo'] //required
static constraints = {
photo contentType: ['image/jpeg','image/png'], fileSize:1024*1024 // 1mb
}
}
GSP
<g:uploadForm name="myUpload" controller="upload" action="updateStatus">
<input type="file" name="myFile" />
</g:uploadForm>
Controller
class PhotoController {
def upload() {
def photo = new Photo(params)
if(!photo.save()) {
println "Error Saving! ${photo.errors.allErrors}"
}
redirect view: "index"
}
}
Sources
1. uploadFrom
2. selfie plugin

Resources