2013-01-24 39 views
0

我試圖用GRAILS實現簡單的上傳/下載文件到/從數據庫功能。除了text/html文件之外,一切看起來都很好。如何使用GRAILS從數據庫下載html文件?

域:

class Content { 
    byte[] file; 
    //filesProperties 
    String contentType 
    String fileName 
    Long size 

    static constraints = { 
     file maxSize: 1024 * 1024 * 20, nullable: true; //20MB 
     fileName nullable:true 
     size nullable:true 
     contentType nullable:true 
    } 
} 

操作:

def getFile() 
{ 
    def content = Content.get(params.id) 
    response.contentType = content.contentType 
    response.setHeader("Content-disposition","attachment;filename="+content.fileName) 
    response.contentLength= content.size 
    response.outputStream << content.file 
    response.outputStream.flush() 

} 

上傳HTML文件之後,一切似乎都在數據庫站點不錯。簡單的SELECT顯示文件已經上傳。 當我嘗試下載html文件時,我找不到頁面(在Chrome net :: ERR_FILE_NOT_FOUND中)。動作getFile()適用於任何其他內容類型。

這種方式是否存在強制下載(不在瀏覽器中顯示)html文件的可能性?

順便說一句:爲什麼顯示它(在Content-Disposition鍵中沒有「attachment」值的response.header)不起作用?

+0

所以你得到了一個404錯誤,當Web瀏覽器試圖呈現的文件作爲網頁,這意味着,它實際上並不存在,作爲一個靜態資源。問題是像** H ttp://www.somesite.com/path/file.html**這樣的URL不會被視爲文件下載鏈接。 – coderLMN

+0

我的網址是:http:// localhost:8080/MyApp/content/getFile/6其中6是內容ID。爲什麼html文件應該是一個靜態資源,例如pdf或txt不是? – kmb

+0

這是一個請求url,但返回的html文件作爲響應會使瀏覽器感到困惑,因爲瀏覽器可能會針對每個請求預計一個html文件。 – coderLMN

回答

1

你可以嘗試強制下載:

response.setHeader("Content-Type: application/force-download");