Downloading files from web url using Coldfusion

I allow the user to upload a file via a form online:

<form action="upload.htm" enctype="multipart/form-data" name="upload_form" method="post">
<input type="file" name="upfile">
<input type="submit" name="upload" value="Upload Photos">
</form>

      

Then on the back, cdfile dumped the file:

<cffile action="upload" destination="#currentpath#" accept="image/jpeg, image/gif, image/png" fileField="form.upfile" nameconflict="makeunique">

      

Now I want to do an automation so that the image file doesn't have to sit on the user's computer, but rather from a web address, for example. http://www.sample.com/images/myimage.jpg instead of c: /images/myimage.jpg

I've tried this:

<cfhttp method="get" url="http://www.example.com/images/myimage.jpg"  resolveurl="Yes" throwOnError="Yes">
<cfif cfhttp.mimeType eq "image/jpeg">
    <cfset currentpath = expandpath('/test/')>
    <cffile action="upload" destination="#currentpath#" accept="image/jpeg, image/gif, image/png" fileField="#cfhttp.fileContent#" nameconflict="makeunique">
</cfif>

      

However, this gives me an error:

Invalid content type: ''. File upload action requires forms to use enctype = "multipart / form-data"

I am not using a form to upload, but it seems to require a form field.

So I tried this:

<cfhttp method="get" url="http://www.example.com/images/myimage.jpg"  resolveurl="Yes" throwOnError="Yes">
<cfif cfhttp.mimeType eq "image/jpeg">
    <cfset currentpath = expandpath('/test/')>
    <cffile action="write" output="#cfhttp.fileContent#"  file="#currentpath#/someimage.jpg">
</cfif>

      

This file writes out a "file" called someimage.jpg, but the output is NOT a jpg file, but something unrecognizable. With cdfile "write" it doesn't allow you to check the image type or the same filename.

Any help is appreciated. Thank you in advance.

+3


source to share


1 answer


Assuming the call was successful, the current code can retrieve and / or store the response as text rather than binary, which could damage the image. To ensure that a binary image is returned, use getAsBinary="yes"

.

Having said that, it's easier to store the response to the file directly in the cfhttp call:



<cfhttp url="http://www.example.com/images/myimage.jpg" 
    method="get" 
    getAsBinary="yes"
    path="#currentpath#" 
    file="someimage.jpg"
    resolveurl="Yes" 
    throwOnError="Yes" />

      

+4


source







All Articles