使用Coldfusion从web url上载文件

使用Coldfusion从web url上载文件,coldfusion,upload,cfhttp,cffile,Coldfusion,Upload,Cfhttp,Cffile,我一直允许用户通过以下在线表单上传文件: <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> 然后在后端,cffile

我一直允许用户通过以下在线表单上传文件:

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

然后在后端,cffile将上载该文件:

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

现在我想实现自动化,这样图像文件就不必位于用户的计算机中,而是来自web目的地,例如,而不是c:/images/myimage.jpg

我试过这个:

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

但是,它给了我一个错误:

无效的内容类型:“”。“文件上载”操作要求表单 使用enctype=“多部分/表单数据”

我没有使用表单上传,但它似乎需要一个表单字段

所以我试了一下:

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

这一个写出了一个名为someimage.jpg的“文件”,但输出不是一个jpg文件,而是一些无法识别的东西。对于cffile“write”,它不允许检查图像类型或相同的文件名


感谢您的帮助。提前感谢。

假设调用成功,当前代码可能正在检索和/或将响应保存为文本,而不是二进制,这将损坏图像。要确保返回二进制图像,请使用
getAsBinary=“yes”

话虽如此,将响应直接保存到调用中更简单:



我没有使用表单上传,但它似乎需要表单字段。是的,“上传”需要一个表单字段,但是。。这不是代码所做的。上载将文件从客户端计算机传输到CF服务器。cfhttp调用是服务器到服务器的。在这种情况下,它会将一个文件从远程下载到CF服务器上。谢谢!这在检索文件时起作用。但是,如何确保用户输入URL包含图像文件?我还需要确保输出文件名与输入文件名相同。有没有办法从cfhttp获取文件名?那将是另一个问题。这个问题已经得到了回答。@DanBracuk这个问题是关于从网络上检索图像文件的。这就是为什么在原始代码中会检查图像文件,然后写入文件。如果您知道答案,如果您能让我知道,我将不胜感激。@Jack-是的,但主要问题是为什么图像保存不正确。答案是,确保图像保存为二进制而不是文本。如何验证URL存在并验证特定内容类型的问题是一个单独的主题。话虽如此,您是否尝试将
getAsBinary=“yes”
添加到代码中?这可能就是你所需要的。如果没有,您应该打开一个关于如何验证url和类型的单独线程。这将使下一个遇到该问题的人更容易找到该线程。@Leigh仅设置getAsBinary=“yes”并不能确保只下载图像。我也可以用它加载pdf。我想在服务器上加载后,我必须进行isimagefile检查。