2014-09-11 160 views
2

在我的Grails應用程序中,我有一個控制器函數來返回PDF文件。Grails - 在瀏覽器中顯示PDF而不是下載

當我調用URL(返回文件)時,它下載文件,而不是在瀏覽器中顯示PDF文件。

當我從其他網站打開其他pdf文件時,它顯示在瀏覽器中..所以我認爲這與我的返回響應有關?

def separator = grailsApplication.config.project.separator.flag 
def path = grailsApplication.config.project.images.path+"public/"+user.id+"/" 
render(contentType: "multipart/form-data", file: new File(path+note.preview), fileName: note.preview) 

我需要更改contentType嗎? (我試圖使它/應用程序/ pdf,但沒有工作?..仍然下載。

回答

2

嘗試設置content-disposition內聯。Content-Type告訴瀏覽器它是什麼類型的內容,但配置告訴瀏覽器如何處理它。

更多信息in this answer

+0

如何設置內容處置..當我嘗試response.setHeader,然後調用渲染後,我認爲它覆蓋它? – 2014-09-11 13:14:59

+0

你可以直接寫入輸出流嗎?例如: 'response.outputStream << your_file response.outputStream.flush()' – prabugp 2014-09-11 13:19:48

+0

我嘗試了以下方法,但沒有運氣---> response.setHeader「Content-disposition」,「inline; filename = 「+ note.preview \t \t response.contentType = '應用/ PDF' \t \t response.outputStream <<新的文件(路徑+ note.preview) \t \t response.outputStream.flush() – 2014-09-11 13:30:05

1

有東西返回一個「文件」的對象,而不是一個byte []對象越來越腐敗。

所以我添加以下行。

byte[] DocContent = null; 
DocContent = getFileBytes(path+note.preview); 

response.setHeader "Content-disposition", "inline; filename="+note.preview+"" 
response.contentType = 'application/pdf' 
response.outputStream << DocContent 
response.outputStream.flush() 


public static byte[] getFileBytes(String fileName) throws IOException 
{ 
    ByteArrayOutputStream ous = null; 
    InputStream ios = null; 
    try 
    { 
     byte[] buffer = new byte[4096]; 
     ous = new ByteArrayOutputStream(); 
     ios = new FileInputStream(new File(fileName)); 
     int read = 0; 
     while ((read = ios.read(buffer)) != -1) 
      ous.write(buffer, 0, read); 
    } 
    finally 
    { 
     try 
     { 
      if (ous != null) 
       ous.close(); 
     } 
     catch (IOException e) 
     { 
      // swallow, since not that important 
     } 
     try 
     { 
      if (ios != null) 
       ios.close(); 
     } 
     catch (IOException e) 
     { 
      // swallow, since not that important 
     } 
    } 
    return ous.toByteArray(); 
} 
相關問題