我知道這裏有幾個關於這方面的問題,但這些解決方案都不起作用。Grails下載zip文件(瀏覽器下載文件)
我試圖點擊一個div,這反過來jQuery使get
請求我的控制器,並最終下載靜態文件(Zip)。使用chrome開發工具,我看到請求會以有效的方式返回200.請求的響應似乎是chrome的嘗試渲染,但我可以確定zip文件中包含的文件的名稱,所以我可以告訴它發現一切正確。
的響應頭:
Content-Type:application/zip
Content-disposition:attachment;filename=myFile.zip
Date:Thu, 12 Jul 2012 20:18:05 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
我的控制器邏輯:
def root = request.getSession().getServletContext().getRealPath("/")
def file = new File("C:\path\to\my\file")
if (file.exists()) {
def os = response.outputStream
response.setHeader("Content-Type", "application/zip")
response.setHeader("Content-disposition", "attachment;filename=${file.name}")
def bytes = file.text.bytes
for(b in bytes) {
os.write(b)
}
os.flush()
org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes().renderView = false
}
我不知道爲什麼我的瀏覽器是不實際下載文件。我已經嘗試了很多不同的控制器邏輯變體,但都具有相同的結果。
有些事情我已經試過:
- 內容類型爲「應用程序/八位字節流;」
response.outputStream << file.bytes
response.outputStream << file.newInputStream()
- 我添加的內容長度
- 流之後移動內容類型寫入
我使用Grails 2.0.4
如果我正確理解你,你正試圖從ajax請求下載文件。這並不真正起作用。 JavaScript並不是真正用於處理這種二進制數據的。是這樣嗎? – Gregg 2012-07-12 20:48:06
希望javascript不需要對二進制文件進行任何操作。JavaScript應該只是簡單地提出一個Web請求 – OnResolve 2012-07-12 21:13:54
不,這不是它的工作原理。您無法通過Ajax請求下載文件。 – Gregg 2012-07-12 21:15:54