簡體   English   中英

如何強制在網址中下載pdf?

[英]How can I force a download of a pdf in a url?

我有一個轉到pdf文件的URL。 在我的Coldfusion頁面中,我希望允許用戶下載文件(使用“打開/保存”對話框或由特定的瀏覽器處理)。

這是我到目前為止的代碼:

<cfset tempFile = getTempFile(getTempDirectory(), 'testfile') />
<cfhttp url="myUrl/myFile.pdf" method="get" file="#tempFile#"/>

<cfheader name="Content-Disposition" value="attachment; filename=myFile.pdf">
<cfcontent type="application/pdf" file="#tempFile#">

這似乎可行...但是當我嘗試打開文件時,它告訴我文件有問題。 我究竟做錯了什么?

文件屬性: 請勿在此屬性中指定目錄的路徑 使用path屬性。

嘗試分隔文件名和路徑:

<!--- hard coded for clarity --->
<cfhttp url="http://www.somesite.com/path/testFile.pdf" 
        method="get" 
        getAsBinary="yes"
        path="c:/test/" 
        file="testFile.pdf"/>

<cfheader name="Content-Disposition" value="attachment; filename=myFile.pdf" />
<cfcontent type="application/pdf" file="c:/test/testFile.pdf" />

對於較小的文件,您可以跳過臨時文件,並使用<cfcontent variable..>

<cfhttp url="http://download.macromedia.com/pub/documentation/en/coldfusion/mx7/cfmx7_cfml_qref.pdf" 
        method="get" 
        getAsBinary="yes" />

<cfheader name="Content-Disposition" value="attachment; filename=myFile.pdf" />
<cfcontent type="application/pdf" variable="#cfhttp.fileContent#" />

更新:使用臨時文件的動態示例

<cfset tempDir  = getTempDirectory() />
<cfset tempFile = getFileFromPath(getTempFile(tempDir, "testfile")) />

<!--- uncomment to verify paths 
<cfoutput>
    tempDir = #tempDir#<br />
    tempFile = #tempFile#<br />
</cfoutput>
<cfabort />
--->
<cfhttp url="http://download.macromedia.com/pub/documentation/en/coldfusion/mx7/cfmx7_cfml_qref.pdf" 
        method="get" 
        getAsBinary="yes"
        path="#tempDir#" 
        file="#tempFile#" />

<cfheader name="Content-Disposition" value="attachment; filename=myFile.pdf" />
<cfcontent type="application/pdf" file="#tempDir#/#tempFile#" />

據我所知,您的編碼在Google Chrome中是可以的。 在IE中,錯誤消息提示。 這是因為“ 文件路徑 ”無法支持URL路徑。 應該使用目錄路徑而不是URL路徑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM