Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coldfusion How to save PDF Response Stream to File

Tags:

coldfusion

We have a REST API that returns a stream of content-type application/pdf. I just want to save it to a file on the server.

<cfhttp url="#ApiPath#" method="post" result="res">
     <cfhttpparam type="header" name="Content-Type" value="application/json" />
     <cfhttpparam type="body" value="#payload#" />
</cfhttp>

<cffile  action = "write" file = "#FileName#" output = "#res.fileContent#">

I've producing a blank PDF, any ideas? ( ive tried various combinations of cfdocument/cfpdf with no luck)

here's a dump of the REST response:

enter image description here

like image 794
Sajjan Sarkar Avatar asked Sep 17 '20 20:09

Sajjan Sarkar


Video Answer


1 Answers

I think I've got it:

Solution 1:

<cfhttp url="#url#" method="post" result="res">
    <cfhttpparam type="header" name="Content-Type" value="application/json" />
    <cfhttpparam type="body" value="#payload#" />
</cfhttp>
<cfset bytes  = res.FileContent.toByteArray()>
<cfscript>    
    fos = createObject("java", "java.io.FileOutputStream").init("myfile.pdf");
    fos.write(bytes);
    fos.flush();
    fos.close();
</cfscript>

EDIT: Based on SOS's solution this also worked:

Solution 2:

<cfhttp url="#url#" method="post" result="res" getAsBinary="Auto">
    <cfhttpparam type="header" name="Content-Type" value="application/json" />
    <cfhttpparam type="body" value="#payload#" />
</cfhttp>

<cfset fileName = listlast(res["responseHeader"]["content-disposition"],";=")>
<cffile action="write" file="#path#\#fileName#" output="#res.FileContent#">
like image 171
Sajjan Sarkar Avatar answered Sep 27 '22 16:09

Sajjan Sarkar