Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create file in memory and let user download

I am coming from razor in asp.net. Usually I would use a [FilePost] for this, but not sure how to do it in grails. Here is the situation

I have a controller

class MyController{
def index{ }
}

I then have a link on index in the form of

<g:link controller="MyController" action="downloadFile">Download</g:link><br>

What I want this to do is take a string (doesn't matter what it is) and I want it to prompt the user to download a text file containing that string. Thanks!

like image 460
Badmiral Avatar asked Jan 21 '13 01:01

Badmiral


3 Answers

Working Solution:

def downloadFile =
{
    File file = File.createTempFile("temp",".txt")
    file.write("hello world!")
    response.setHeader "Content-disposition", "attachment; filename=${file.name}.txt"
    response.contentType = 'text-plain'
    response.outputStream << file.text
    response.outputStream.flush()
}
like image 196
Badmiral Avatar answered Nov 13 '22 12:11

Badmiral


So probably something like this:

byte[] bytes = "string".bytes

response.setContentType("text/plain")
response.setHeader("Content-disposition", "filename=\"xyz.txt\"")
response.setContentLength(bytes.size())
response.outputStream << bytes
like image 42
James Kleeh Avatar answered Nov 13 '22 10:11

James Kleeh


What is preventing you from creating the bytes yourself and feeding it to the outputstream? String.getbytes or bytes created from a business method of yours for example.

like image 34
rimero Avatar answered Nov 13 '22 11:11

rimero