5

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!

Badmiral
  • 1,549
  • 3
  • 35
  • 74
  • See similar question with answer http://stackoverflow.com/questions/6111255/grails-file-download. – rimero Jan 21 '13 at 02:11
  • I saw that one, but that takes a file that already exists and downloads it, I want to make a file on the fly – Badmiral Jan 21 '13 at 02:13

4 Answers4

4

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()
}
Badmiral
  • 1,549
  • 3
  • 35
  • 74
4

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
James Kleeh
  • 12,094
  • 5
  • 34
  • 61
1

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.

rimero
  • 2,383
  • 1
  • 14
  • 8
0

In header again .txt file extension is not required.

Ravi Macha
  • 687
  • 8
  • 5