save image to a folder under web-app in grails -
i need save image folder in application. far have learned save image database need save folder. how can this? can please me on please? here code below save database >>>
def upload={ def user = user.findbyid(1) commonsmultipartfile file = params.list("photo")?.getat(0) user.avatar = file?.bytes user.save() }
find below step wise implementation, have added gsp page uploadform(it have multipart form submission default), , controller function handle file save request, , service method save file in specified directory:
step1: create form file upload:
<g:uploadform name="picuploadform" class="well form-horizontal" controller="<your-controller-name>" action="savepicture"> select picture: <input type="file" name="productpic"/> <button type="submit" class="btn btn-success"><g:message code="shopitem.btn.saveproductimage" default="save image" /></button> </g:uploadform>
step2: in controller's savepicture action:
string baseimagename = java.util.uuid.randomuuid().tostring(); // saving image in folder assets/channelimage/, in web-app, name: baseimagename def downloadedfile = request.getfile( "product.baseimage" ) string fileuploaded = fileuploadservice.uploadfile( downloadedfile, "${baseimagename}.jpg", "assets/channelimage/" ) if( fileuploaded ){ // further actions, example make db entry file name }
step3: , in file uploader service(user defined service name fileuploadservice in case):
def string uploadfile( multipartfile file, string name, string destinationdirectory ) { def serveletcontext = servletcontextholder.servletcontext def storagepath = serveletcontext.getrealpath( destinationdirectory ) def storagepathdirectory = new file( storagepath ) if( !storagepathdirectory.exists() ){ println("creating directory ${storagepath}") if(storagepathdirectory.mkdirs()){ println "success" }else{ println "failed" } } // store file if(!file.isempty()){ file.transferto( new file("${storagepath}/${name}") ) println("saved file: ${storagepath}/${name}") return "${storagepath}/${name}" }else{ println "file: ${file.inspect()} empty" return null } }
Comments
Post a Comment