从自动下载URL中获取文件(使用ColdFusion)

7

我正试图使用cfhttp从自动下载的URL获取文件。我正在使用以下代码:

<cfhttp method="get" url="http://www.example.com/getfile" path="E:/" file="abc.csv">

在这个例子中,我已经指定了文件类型为CSV,所以我可以获取到这个文件,但是文件类型可能会改变。我尝试使用 CFHTTP.MIMETYPE 来获取文件类型,并像这样使用:
<cfhttp method="get" url="http://www.example.com/getfile">
<cffile action="write" file="E:/abc.#listLast(cfhttp.MIMETYPE,'/')#" output="#cfhttp.FileContent#">

这适用于CSV和XML文件。但我也想让它适用于Excel文件。

请帮助我。 提前致谢。


Сйат░ЮУ»ЋтюеcfhttpТаЄуГЙСИГУ«Йуй«getAsBinary="Auto"С║єтљЌ№╝Ъ - Regular Jo
我可以将它转换为二进制,但怎样获取文件扩展名呢? - Beginner
@cfqueryparam 有没有办法获取文件扩展名? - Beginner
2
倒出cfhttp对象以查看标头。通常,在“Content-Disposition”标头中包括文件名。 - Leigh
@Leigh 是的,在“Content-Disposition”中只有自动下载URL中才有文件名。 - Beginner
显示剩余2条评论
2个回答

5
<cfhttp method="get" url="http://www.example.com/getfile">
<cfset fileName = listlast(cfhttp["responseHeader"]["content-disposition"],";=")>
<cffile action="write" file="E:/abc.#fileName#" output="#cfhttp.FileContent#">

1
为什么要使用两个listlasts?您可以使用一个listlast并同时指定两个分隔符来覆盖它。这是listlast与Java的split不同的地方之一。另外,为什么要使用structfind?cfhttp["responseHeader"]["Content-Disposition"]将具有相同的作用,因为StructFind()会抛出异常,如果键不存在,就像直接调用它一样。虽然这些只是语义问题,但答案是可以的,但是listlast(cfhttp["responseHeader"]["content-disposition"],";=")将实现相同的目标。 - Regular Jo
@cfqueryparam:感谢您的建议。我已经更新了我的答案。 - Deepak Kumar Padhy

1

正如“Regular Jo”所提到的,您需要将getAsBinary =“Auto”添加到cfhttp中才能使其正常工作。感谢Deepak Kumar Padhy提供了最初的答案,指引我朝着正确的方向前进。

<cfhttp method="get" url="http://www.example.com/getfile" getAsBinary="Auto" result="cfhttp">
        
<cfdump var="#cfhttp#">
        
<!--- Returns the file name with double quotes, ex. '"Users.zip"' --->
<cfset fileNameWithQuotes = listlast(cfhttp["responseHeader"]["content-disposition"],";=")>
        
<!--- Remove the '"' in the file name so it is Users.zip --->
<cfset fileName = REPLACENOCASE(fileNameWithQuotes,'"','', 'ALL')>
       
<!--- Write the zip to the server location ---> 
<cffile action="write" file="E:/abc/#fileName#" output="#cfhttp.FileContent#">
        
<!--- if zip file, unzip the file to get the csv --->
<cfzip file="E:/abc/#fileName#" action="unzip" filter="*.csv" destination="E:/abc/" />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接