如何强制在网址中下载pdf?

fro*_*die 8 pdf coldfusion download

我有一个转到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#">
Run Code Online (Sandbox Code Playgroud)

这似乎有效......但是当我尝试打开文件时,它会告诉我文件有问题.我究竟做错了什么?

Lei*_*igh 12

file属性:不指定该属性中目录的路径 ; 使用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" />
Run Code Online (Sandbox Code Playgroud)

对于较小的文件,您可以跳过临时文件并使用 <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#" />
Run Code Online (Sandbox Code Playgroud)

更新: 使用临时文件的动态示例

<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#" />
Run Code Online (Sandbox Code Playgroud)