Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

coldfusion - How can I force a download of a pdf in a url?

I have a URL that goes to a pdf file. In my coldfusion page, I want to allow the user to download the file (using the open/save dialog or however that particular browser handles it).

This is the code I have so far:

<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#">

This seems to work... but when I try to open the file it tells me something's wrong with the file. What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

file attribute: Do not specify the path to the directory in this attribute; use the path attribute.

Try separating the file name and 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" />

For smaller files you might skip the temp file and use <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#" />

Update: Dynamic example using a temp file

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...