Sunday, September 7, 2014

ColdFusion CFHTTP and WebDav

As it turns out, I recently ran into the need to interface with a WebDAV server via ColdFusion. Surprisingly, there is practically no information online regarding this topic. I just wrapped up a test PUT file snippet and figured I would share it with all you ColdFusioneers who aren't finding the copy/paste you are looking for :-).

First off, you can't simply use cfhttpparam type="file" as you'll end up sending file data with headers included in the body of the request. The WebDAV server will write these headers into the file content and you'll end up with a corrupted file. Instead, the WebDAV spec calls for the entire body of the request to be file data.

That leads us to the following code. You'll see this is uploading a simple jpeg to the WebDAV server. The cffile readbinary file attribute is being set to the full local file path. The cfhttpparams include the typical Content-Type header, but also Overwrite and Translate which are commonly supported and sometimes required by WebDAV servers. The body of the request is the raw binary file data. Simple!

<cffile action="readBinary" file="#loc.images[curr_image]#" variable="loc.curr_binary">
<cfhttp method="PUT"
username="#This.webDAVsettings.username#" password="#This.webDAVsettings.password#"
<cfhttpparam type="header" name="Content-Type" value="image/jpeg">
<cfhttpparam type="header" name="Overwrite" value="T">
<cfhttpparam type="header" name="Translate" value="F">
<cfhttpparam type="body" value="#loc.curr_binary#">

No comments:

Post a Comment