Tuesday, 21 June 2016

File Upload, Display and Download

File Upload:

Step 1:

html code

<input type="file" class="form-control" name="img" id="img"/>

Step 2:

controller side

properties.imgFile = request.getFile('img')
MultipartFile img;
def file = properties.imgFile
String extractedName = FilenameUtils.removeExtension(file.originalFilename)
String extension = FilenameUtils.getExtension(file.originalFilename)
def fileName = account.id +"."+extension//Get An Account ID On the Image Name
def storage =  messageSource.getMessage('com.gb.storageLocation',null,LCH.getLocale())
def folder = new File(storage)
def imagePath = storage+File.separator+fileName
if( !folder.exists())  folder.mkdirs()
if(extension) {
file.transferTo(new File(imagePath))
account.img = imagePath
}


Display:

html code

<img  class="ts-avatar hidden-side" alt="" src="<g:createLink controller="Setups" action="viewImage" params='[title: "${session?.loggedInUser?.account?.img}"]'/>"/>

controller side

def viewImage(){
try{
def file = new File(params.title)
def img = file.bytes
response.contentType = 'image/jpg,image/png' // or the appropriate image content type
response.outputStream << img
response.outputStream.flush()
}catch(Exception e){
}
}

Download:

def downloadExcel(fileName) {
def file = new File(servletContext.getRealPath("/dataCsv/"+fileName))
if (file.exists()) {
response.setContentType("application/vnd.ms-excel")
if(params.action == "productListExcelDownload") response.setHeader('Content-Disposition', "Filename="+"ProductList")
else  response.setHeader('Content-Disposition', "Filename="+fileName)
response.outputStream << file.bytes
if(params.action == "productListExcelDownload") {
String realPath  = ServletContextHolder.servletContext.getRealPath(File.separator+"dataCsv"+File.separator+"ProductList");
File f =new File (realPath);
if(f.isDirectory()) {
f.deleteDir()
}
}
}
return
}


No comments:

Post a Comment