uploading a file in grails - 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

Related

Liferay Upload : UploadPortletRequest empty

I am having an issue getting multiple file from an upload using the UploadPortletRequest.
I can see in my ActionRequest that the files are here: using debug i see that actionRequest.multipartFiles.[0].fileItem.tempFile give me the location of the first uploaded file.
Though, in order to get the multipartParameterMap I need to convert the ActionRequest in UploadPortletRequest. when I do :
UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
My uploadRequest.getSize("fileName")) returns 0...
Do you know what could be the cause?
Do you have another solution to get the temp uploaded files from the ActionRequest ?
Here is the .jsp I use :
<portlet:actionURL var="fileUploadURL">
<portlet:param name="formAction" value="fileUpload" />
</portlet:actionURL>
<form:form name="fileUploader" commandName="springFileVO"
method="post" action="${fileUploadURL}" enctype="multipart/form-data">
<label> Select a File</label>
<input type="file" name="uploadedFile" multiple="multiple">
<input type="submit" value="<liferay-ui:message key="upload" />" onClick="<%= uploadProgressId %>.startProgress(); return true;"/>
</form:form>
<liferay-ui:upload-progress id="<%= uploadProgressId %>" message="uploading" redirect="<%= HtmlUtil.escape(fileUploadURL) %>" />
Here is the Controller :
#ActionMapping(params="formAction=fileUpload")
public void fileUpload(ActionRequest request, ActionResponse response){
UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(request);
System.out.println("Size: "+uploadPortletRequest.getSize("uploadedFile"));
[...] }
Thank you for your help!
I think you're missing portlet:namespace attribute.
<input type="file" name="<portlet:namespace/>uploadedFile" multiple="multiple">
As your uploading multiple files, you can use following.
UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(request);
File[] files = uploadPortletRequest.getFiles("uploadedFile");
for (File file : files) {
System.out.println("Size: "+ file.length());
}

Couldn't upload file at any cost in 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!")
}

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

How to save uploaded image

I'm wondering how I could save an uploaded image in grails.
The situation:
I have a gsp page with a form, containing a file upload. I tried to get the data from the fileupload, but it just won't work.
In the controller:
def file = request.getFile('fileupload')
appearanceInstance.logo = file.encodeAsBase64().toString()
In the view:
<g:form action="save" enctype="multipart/form-data">
<div class="file-upload">
<label >Choose logo</label>
<input id="fileupload" type="file" name="fileupload" onchange="handleFileSelect(this)"/>
</div><br/>
<br/>
</g:form>
Anyone who had experience with this?
this might be another way to do it, but since I adapt an in the view when an image is selected using the file upoad, can I get the image data from the in the controller?
Thanks in advance!
UPDATE:
to be clear, there are some other controls in the form, from which I get the other parameters to save.
I guess this example Simple Avatar Uploader will answer all your questions
try this i hope this will help you it works for me also see this post
Class SomeController{
def uploader(){
}
def save(){
String s=""
CommonsMultipartFile f=request.getFile('fileupload')
final String name =f.getOriginalFilename()
def fos= new FileOutputStream(new File(name))
f.getBytes().each{ fos.write(it) }
s=Base64.encode(f.getBytes())
fos.flush()
fos.close()
render 'done now refresh your source directory to see the file ${s}'
}
and the view 'uploader.gsp'
<g:form action="save" enctype="multipart/form-data">
<div class="file-upload">
<label>Choose logo</label> <input id="fileupload" type="file"
name="fileupload" />
</div>
<input type="submit" class="buttons" value="Upload" />
</g:form>
Hi try with this one .
def save = {
def requestInstance = new Request(params)
def requestNumberInstance = new RequestNumber()
if(requestInstance.validate() && requestInstance.save(flush: true)){
println "Saved successfully with ${requestInstance.picture1.length} bytes"
}
else {
println "Save failed"
}

Resources