Download Grails File

I used the this method to copy the file to a folder in my project (the first method), and I edited it so that the location is stored on my "Location" in the class view (see below).

Now I want to download this file after clicking on the image in my view. How can i do this?

class Submissions { Date dateSub String Location String fileName } 
+6
source share
4 answers

I did something similar to the following:

Assuming your download page has an appropriate instance of Submissions ...

 <g:link action="downloadFile" id="${aSubmission.id}"> <img>...etc...</img> </g:link> 

Then in the controller (is your "location" the path to the file?):

 def downloadFile = { def sub = Submissions.get(params.id) def file = new File("${sub.location}/${sub.fileName") if (file.exists()) { response.setContentType("application/octet-stream") // or or image/JPEG or text/xml or whatever type the file is response.setHeader("Content-disposition", "attachment;filename=\"${file.name}\"") response.outputStream << file.bytes } else render "Error!" // appropriate error handling } 
+20
source

Well, it's always better to keep the loading logic wrapped inside try / catch, and set webrequest to false. http://lalitagarw.blogspot.in/2014/03/grails-forcing-file-download.html

 def downloadFile() { InputStream contentStream try { def file = new File("<path>") response.setHeader "Content-disposition", "attachment; filename=filename-with-extension" response.setHeader("Content-Length", "file-size") response.setContentType("file-mime-type") contentStream = file.newInputStream() response.outputStream << contentStream webRequest.renderView = false } finally { IOUtils.closeQuietly(contentStream) } } 
+2
source

you just need to display the bytes in the response. We are doing something like

 def streamFile = { // load the attachment by id passed on params .... response.contentType = attachment.contentType.toLowerCase() response.contentLength = attachment.data.length() // our 'data' field is a Blob, the important thing here is to get the bytes according to // how you get the actual downlaod response.outputStream.write(attachment.data.getBytes(1L, attachment.data?.length() as int)) } 

in our controller and just create a link to this controller method on gsp. Depending on how you use the content type, the browser will do something for you. For example, if you have an image type, it will display the image. If you have a document with text, the browser should open the appropriate program for the user system.

+1
source

I used the FCKEditor WYSIWYG editor http://www.grails.org/plugin/fckeditor , it is also an easy to use file downloader.

+1
source

Source: https://habr.com/ru/post/888900/


All Articles