使用 Coldfusion 从 web url 上传文件

Jac*_*ack 4 coldfusion upload cffile cfhttp

我一直允许用户通过在线表单上传文件,如下所示:

<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>
Run Code Online (Sandbox Code Playgroud)

然后在后端,cffile 将上传文件:

<cffile action="upload" destination="#currentpath#" accept="image/jpeg, image/gif, image/png" fileField="form.upfile" nameconflict="makeunique">
Run Code Online (Sandbox Code Playgroud)

现在我想做自动化,以便图像文件不必位于用户的计算机中,而是来自网络目的地,例如http://www.sample.com/images/myimage.jpg而不是 c:/images/我的图片.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>
Run Code Online (Sandbox Code Playgroud)

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

无效的内容类型:''。文件上传操作需要表单使用 enctype="multipart/form-data"

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

所以我试过这个:

<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>
Run Code Online (Sandbox Code Playgroud)

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

任何帮助表示赞赏。先感谢您。

Lei*_*igh 5

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

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

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

  • 那将是一个不同的问题。这个已经回答了。 (3认同)