我想要使用Grails控制器方法呈現或下載鏈接到PDF的URL。我可以打開這是在一個新的或相同的標籤,或只是下載它。這在Grails中如何完成?在Grails控制器中打開或下載URL鏈接
到目前爲止,我有:
render(url: "http://test.com/my.pdf")
不過,我得到這個和其他方法我試過,例如渲染與內容的響應錯誤。任何線索?
我想要使用Grails控制器方法呈現或下載鏈接到PDF的URL。我可以打開這是在一個新的或相同的標籤,或只是下載它。這在Grails中如何完成?在Grails控制器中打開或下載URL鏈接
到目前爲止,我有:
render(url: "http://test.com/my.pdf")
不過,我得到這個和其他方法我試過,例如渲染與內容的響應錯誤。任何線索?
一種選擇是
class ExampleController {
def download() {
redirect(url: "http://www.pdf995.com/samples/pdf.pdf")
}
}
要localhost:8080/appName/example/download
將根據用戶的瀏覽器偏好,無論是下載文件或打開在同一選項卡中的文件進行讀取。
我使用grails 2.5.0
是的,你完全可以做到這一點很容易:
首先從URL中的文件(如果你沒有一個本地文件),例如:
class FooService {
File getFileFromURL(String url, String filename) {
String tempPath = "./temp" // make sure this directory exists
File file = new File(tempPath + "/" + filename)
FileOutputStream fos = new FileOutputStream(file)
fos.write(new URL(url).getBytes())
fos.close()
file.deleteOnExit()
return file
}
}
現在在你的控制器,做這允許用戶自動下載PDF文件:
class FooController {
def fooService
def download() {
String filename = "my.pdf"
// You can skip this if you already have that file in the same server
File file = fooService.getFileFromURL("http://test.com/my.pdf", filename)
response.setContentType("application/octet-stream")
response.setHeader("Content-disposition", "${params.contentDisposition}; filename=${filename}")
response.outputStream << file.readBytes()
return
}
}
現在,作爲用戶將達到/foo/download
文件將被自動dowloaded。
我可以下載我的文件。但我需要在新標籤中顯示我的PDF文件,現在應該怎麼做,我可以在哪裏獲得URL? –
您想要在控制器中下載URL的目標。並可能將其存儲在本地(在服務器上),然後提供它?或者你想顯示用戶到PDF的鏈接?並可能通過Grails發佈PDF文件? – defectus
我很好,只需自動下載到'Downloads'目錄。就像,當你點擊頁面上的任何鏈接,並自動下載它 – reectrix
我不確定你能做到這一點。讓請求返回JSON會更容易(例如'render([url:「http://test.com/my.pdf」]爲JSON)'),並且在客戶端有Javascript來打開鏈接(' window.open(response.url);')? – lvojnovic