如何强制下载url中的pdf?

如何强制下载url中的pdf?,pdf,coldfusion,download,Pdf,Coldfusion,Download,我有一个指向pdf文件的URL。在我的coldfusion页面中,我希望允许用户下载该文件(使用“打开/保存”对话框或特定浏览器处理该文件的方式) 这是我目前掌握的代码: <cfset tempFile = getTempFile(getTempDirectory(), 'testfile') /> <cfhttp url="myUrl/myFile.pdf" method="get" file="#tempFile#"/> <cfheader name="Con

我有一个指向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#">

这似乎有效。。。但是当我试图打开文件时,它告诉我文件有问题。我做错了什么

文件属性:指向该属性中的目录;使用 路径属性

尝试分离文件名和路径:

<!--- 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" />

对于较小的文件,您可以跳过临时文件并使用



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

<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路径。

试试
method=“getAsBinary”
。您可能需要同时提供
文件
路径
@leigh-method=“getAsBinary”抛出错误。。。你是说getAsBinary=“是的”?是的。我的错。我在那里加了一点;)@利-试过了,没用…:(你所说的目录路径和位置是什么意思?谢谢!分离文件名和路径没有帮助,但是第二个建议(使用变量)起了作用!这是令人惊讶的。这两个代码片段在CF9下对我都起了作用。只是好奇,你用了什么代码来分离路径?我用的是CF8。我保存了
getTempDirectory()
转换为一个变量,而不是在运行中使用它来获取临时文件,因此我有了路径,并使用类似于
listLast(tempFile,“/”)的东西分隔了文件名。
@froadie-对我来说非常适合。我不认为这是版本问题。请仔细检查您的变量。确保它们是您认为的;)请参阅更新。
<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#" />