Ask Ben: Posting XML And File Data With ColdFusion And CFHttp

Posted December 4, 2008 at 12:25 PM by Ben Nadel

Tags: ColdFusion, Ask Ben

I am using CFHTTP to send a multipart message XML and an image file (fax tiff), the question I have is how do you send a XML type and File type in the same post? I have tried using cfhttp type designator, but cold fusion errors saying that you can not have both a XML and File type.

The problem here is that you are using the ColdFusion CFHttpParam type of "XML". If you use CFHttpParam type of "XML" or "Body", you cannot mix in other pieces of data because XML and Body are designed to be the only data going across (the entire body of the message). In fact, if you designate the type, XML, behind the scenes, it is actually using type, Body, and setting the mime type to be "text/xml". As such, the XML type is merely a short-hand for the type Body.

If you try to mix and match, you will get the following ColdFusion error (as you have probably seen):

You cannot mix the use of cfhttpparam tags of type file or formfield with cfhttpparam tags of type body or XML.

This is not a problem, however; all we need to do is not use type XML or Body when posting multiple pieces of information. If we need to POST some XML and a file, let's just treat this like it's a standard form post and post each of these datum as if they were form data:

  • <!--- Define our generic CFHTTP properties. --->
  • <cfset objCFHttpProperties = {
  • Useragent = "#CGI.http_user_agent#",
  • Username = "xxxxxxx",
  • Password = "yyyyyyy"
  • } />
  •  
  •  
  • <!---
  • Get the URL for our post. Since CFHttp requires a full
  • URL, not just a relative one, we need to build it.
  • --->
  • <cfset strURL = (
  • CGI.server_name &
  • GetDirectoryFromPath( CGI.script_name ) &
  • "cfhttp_catch.cfm"
  • ) />
  •  
  •  
  • <!--- Create the XML data to post. --->
  • <cfxml variable="xmlPurchaseData">
  •  
  • <transaction>
  • <type>Debit</type>
  • <cost>19.95</cost>
  • <date>12-04-2008</date>
  • <item>
  • <sku>BTC-CANADA-07189</sku>
  • <name>Better Than Chocolate</name>
  • </item>
  • </transaction>
  •  
  • </cfxml>
  •  
  •  
  • <!--- Create the file path to the DVD cover. --->
  • <cfset strFilePath = ExpandPath( "./cover.jpg" ) />
  •  
  •  
  • <!---
  • Now, we are going to post the XML data along with the
  • cover of the movie that we are pretending to purchase.
  • --->
  • <cfhttp
  • url="#strURL#"
  • method="POST"
  • result="objGet"
  • attributecollection="#objCFHttpProperties#">
  •  
  • <!---
  • When posting the XML data, ColdFusion will worry
  • about converting the XML document back into a string.
  • --->
  • <cfhttpparam
  • type="formfield"
  • name="purchase_data"
  • value="#xmlPurchaseData#"
  • />
  •  
  • <!--- Post the file. --->
  • <cfhttpparam
  • type="file"
  • name="cover"
  • file="#strFilePath#"
  • mimetype="image/jpeg"
  • />
  •  
  • </cfhttp>
  •  
  •  
  • <!--- Output the return message. --->
  • Message: #objGet.FileContent#

As you can see here, we are performing a FORM POST. The Xml data is being send over as a form field and the file is being sent across as a file (specialized form field). Nothing special going on.

This data is being posted to the following "catch" page:

  • <!--- Param the form fields. --->
  • <cfparam name="FORM.purchase_data" type="string" default="" />
  • <cfparam name="FORM.cover" type="string" default="" />
  •  
  •  
  • <!--- Write the purchase data to file. --->
  • <cffile
  • action="write"
  • file="#ExpandPath( './purchase_data.xml' )#"
  • output="#FORM.purchase_data#"
  • />
  •  
  • <!--- Upload the DVD cover. --->
  • <cffile
  • action="upload"
  • filefield="cover"
  • destination="#ExpandPath( './' )#"
  • nameconflict="makeunique"
  • />
  •  
  •  
  • <!--- Return response string. --->
  • <cfcontent
  • type="text/plain"
  • variable="#ToBinary( ToBase64( 'Processing Done!' ))#"
  • />

This "catch" page looks and acts just like any standard ColdFusion form processing page. We are treating the posted data as if they were FORM-scoped data because, in fact, that is what they are. Once we accept this, we can then process the form data as we would normally (here I am saving the XML and image to file).

I hope this helps.




Reader Comments

Dec 4, 2008 at 12:45 PM // reply »
304 Comments

The problem I have with your solution is that sometimes the receiver of the data requires you to post the data as a multipart http post. Splitting it up into two form fields only works if you have control over the receiver.

As an example, when I had to do my file uploads for youtube (http://youtubecfc.riaforge.org), I had to do both an XML field and a file field. This is the code I used:

<cfhttp url="#theurl#" method="post" result="result" multiparttype="related">
<cfhttpparam type="header" name="Authorization" value="GoogleLogin auth=#variables.authtoken#">
<cfhttpparam type="header" name="X-GData-Client" value="youtubecfc">
<cfhttpparam type="header" name="X-GData-Key" value="key=#variables.devkey#">
<cfhttpparam type="header" name="Slug" value="#listLast(arguments.video,"\/")#">
<cfhttpparam type="file" name="API_XML_Request" file="#tmpfile#" mimetype="application/atom+xml; charset=UTF-8 ">
<cfhttpparam type="file" name="file" file="#arguments.video#" mimetype="video/*">
</cfhttp>

Notice the XML is sent as a file (only sucky part, I had to save the XML string to the file system) and includes a mimetype.

Note - this code makes use of the new multipart=related argument that was added per a hotfix for cf7 and 8. Ie, this is not part of the documented CF language, although it is "official" if you get the hotfix.


Dec 4, 2008 at 12:51 PM // reply »
10,640 Comments

@Ray,

Interesting. I guess I have never had to do a real "multi-part" post. I just thought the Asker meant that he was trying to submit several parts of data. I am assuming he was trying to post XML and File types (which is why he was getting an errror).

This is good to know though - I have never come up against this, so I am sure it will save me headache when I do. Thanks!


Dec 4, 2008 at 1:01 PM // reply »
304 Comments

Don't get me started on Google and their freaking APIs. (Since Google owns YouTube now they had to make the api 'better')


Dec 4, 2008 at 1:04 PM // reply »
10,640 Comments

@Ray,

Ha ha, breathe breathe :)


Sep 14, 2010 at 10:36 AM // reply »
7 Comments

sigh, no luck on railo, multiparttype="related" not supported :((
Anyway I got videos uploaded with CF9 in a few minuts, thanks a lot !!


Sep 14, 2010 at 9:38 PM // reply »
10,640 Comments

@Philippe,

Glad you got it working. I've yet to experiment with the multipartType yet. Thanks for the reminder that this was out there.


Post A Comment

Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Please review the following issues:

Author Name:


Author Email:

Author Website:

Comment:

Supported HTML tags for formatting: <strong>bold</strong>   <em>italic</em>   <code>code</code>







  • Help Wanted - Find Your Next ColdFusion Job
InVision App - Prototyping Made Beautiful With Prototyping Tools Ben Nadel's Company - Epicenter Consulting Recent Blog Comments
Feb 10, 2012 at 7:21 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
Update! Instead of $(eval(options.insertAfter)).after(data['insertData']); I now use: var ajaxNode = document.createElement('span'); var parent = $(eval(options.insertAfter))[0].parentNode; ... read »
Feb 10, 2012 at 6:18 PM
jQuery AJAX Strips Script Tags And Inserts Them After Parent-Most Elements
encountered this same, what I consider, jQuery bug last week. I'm building a site in which I load some content via AJAX. This content contains Linkedin share button placeholders which Linkedin API ne ... read »
Feb 10, 2012 at 11:30 AM
Cross-Origin Resource Sharing (CORS) AJAX Requests Between jQuery And Node.js
After you understand the concepts here, this is an awesome cheatsheet for enabling CORS in just about anything http://enable-cors.org/ ... read »
JM
Feb 10, 2012 at 9:10 AM
My Safari Browser SQLite Database Hello World Example
@Amy, Here is a very good tutorial on how to use JOIN: http://www.sqltutorial.org/sqljoin-innerjoin.aspx ... read »
Feb 10, 2012 at 4:42 AM
Building A Twitter-Inspired RESTful API Architecture In ColdFusion
This is great, very useful Ben. I spotted a small typo in the api.cgm listing: <cfthrow type="Unauthroized" /> Cheers Stefan ... read »
Feb 9, 2012 at 10:35 PM
CFDirectory Filtering Uses Pipe Character For Multiple Filters (Thanks Steve Withington)
I was wondering if there would be a filter you could apply so that you got everything but what you included in the filter. As in show me all docs that are not a .pdf. ... read »
Feb 9, 2012 at 10:29 PM
Learning ColdFusion 9: Application-Specific Data Sources
@Ben, No offence, but if people were really wanting advanced features they would be using a platform like ASP.NET MVC. CFML is so structurally compromised as a tag-based scripting language that ... read »
Feb 9, 2012 at 10:03 PM
Subversion - Cleanup Failed To Process The Following Paths
@Leviaguirre, do you still have problems with this? ... read »