2013-01-21 46 views
5

我來自asp.net中的剃鬚刀。通常我會爲此使用[FilePost],但不知道如何在grails中執行此操作。這裏的情況是在內存中創建文件並讓用戶下載

我有一個控制器

class MyController{ 
def index{ } 
} 

我則具有在

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

形式我想這是做什麼對指數的鏈接需要一個字符串(沒有按」不管它是什麼),我希望它提示用戶下載包含該字符串的文本文件。謝謝!

+0

看到類似的問題與答案 http://stackoverflow.com/questions/6111255/grails-file-download。 – rimero

+0

我看到了一個,但這需要一個已經存在的文件並下載它,我想立即創建一個文件 – Badmiral

回答

4

工作液:

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() 
} 
+0

看到我的文章,您不必創建一個文件 –

4

所以大概是這樣的:

byte[] bytes = "string".bytes 

response.setContentType("text/plain") 
response.setHeader("Content-disposition", "filename=\"xyz.txt\"") 
response.setContentLength(bytes.size()) 
response.outputStream << bytes 
1

什麼阻止您自己創建的字節,將其送入的OutputStream?例如,String.getbytes或從您的業務方法創建的字節。

0

再次在標頭中.txt文件擴展名不是必需的。

相關問題