coldfusion

tech2024-05-09  83

coldfusion

The Hypertext Transfer Protocol, HTTP, was first used in the "World Wide Web global information initiative" in 1990. Since then, it has become a part of our everyday lives, whether we think about it or not.

HTTP ,超文本传输​​协议,最早是在1990年被用于“万维网全球信息倡议”中。从那时起,无论我们是否考虑,它已成为我们日常生活的一部分。

Usually, we make use of this protocol without giving it a second thought, like when we surf the Web. Sometimes, though, we have to actively use HTTP to solve problems. ColdFusion has built-in tags for HTTP support and, as Web developers, it is to our advantage to know how to use these tags efficiently. So, let’s take a trip down HTTP lane and see what can be done with this technology.

通常,我们在使用该协议时不会再三思而后行,就像在浏览Web时一样。 但是,有时我们必须积极使用HTTP来解决问题。 ColdFusion具有用于HTTP支持的内置标签,作为Web开发人员,知道如何有效使用这些标签对我们来说是一个优势。 因此,让我们沿着HTTP路线走一趟,看看该技术可以做什么。

HTTP如何工作 (How HTTP Works)

If we dumb it down to the lowest level, HTTP is a way for clients to request information from a Web server, and for Web servers to provide responses to those requests. When you type https://www.sitepoint.com/ into your browser’s address bar, your browser (the client) sends an HTTP request to SitePoint’s server. SitePoint’s server then processes your request, pulling data out of the database, creating the HTML, and returning it to your browser.

如果我们将其降低到最低水平,HTTP是客户端从Web服务器请求信息以及Web服务器提供对那些请求的响应的一种方式。 当您在浏览器的地址栏中键入https://www.sitepoint.com/时 ,浏览器(客户端)会将HTTP请求发送到SitePoint的服务器。 然后,SitePoint的服务器处理您的请求,从数据库中提取数据,创建HTML,然后将其返回给浏览器。

There are two kinds of requests commonly made to a server: "GET" and "POST" requests (and yes, this is why HTML forms let you set a submission method of "GET" or "POST"). The method used specifies how the data is sent. You’ll notice that if you create a form with the "GET" method, the values entered in the form are passed on the URL. If you use the "POST" method, they are sent behind the scenes. That’s why, for example, Internet Explorer always asks if you want to resend the data when you reload the result of a "POST" request — it’s letting you know that something was sent behind the scenes and must be resent for the request to process correctly.

通常对服务器发出两种请求:“ GET”和“ POST”请求(是的,这就是HTML表单允许您将提交方法设置为“ GET”或“ POST”的原因)。 使用的方法指定如何发送数据。 您会注意到,如果使用“ GET”方法创建表单,则在URL中传递在表单中输入的值。 如果使用“ POST”方法,它们将在后台发送。 例如,这就是为什么Internet Explorer在重新加载“ POST”请求的结果时始终询问您是否要重新发送数据的原因-它使您知道某些内容已在后台发送,并且必须重新发送以使请求正确处理。

We should also touch briefly on MIME types. MIME stands for Multipurpose Internet Mail Extensions. This standard was originally intended to define the types of files that are exchanged via email, but has since been extended to the World Wide Web. Knowing about MIME types will allow us to return information in various formats and it will be a key part of our demonstration code below.

我们还应该简要介绍一下MIME类型。 MIME表示多用途Internet邮件扩展。 该标准最初旨在定义通过电子邮件交换的文件的类型,但此后已扩展到万维网。 了解MIME类型将使我们能够返回各种格式的信息,这将是下面的演示代码的关键部分。

There’s much, much more to HTTP than I’ve described in these brief paragraphs. In fact, entire books have been written on the topic. But, for our purposes, we’ll leave the discussion here. If you want more information, you can find an excellent HTTP reference at the W3C Website.

HTTP的内容比我在这些简短段落中描述的要多得多。 实际上,整本书都写过关于该主题的文章。 但是,出于我们的目的,我们将在此处保留讨论。 如果需要更多信息,可以在W3C网站上找到出色的HTTP参考。

HTTP和ColdFusion –标签 (HTTP and ColdFusion – The Tags)

First, let’s cover the basic tags we’ll be using in our sample application. We’ll be using cfhttp, cfhttpparam, cfheader, and cfcontent.

首先,让我们介绍将在示例应用程序中使用的基本标签。 我们将使用cfhttp , cfhttpparam , cfheader和cfcontent 。

First, let’s look at CFHTTP. The most common use for CFHTTP is to retrieve data from another page or site. For example, if you wanted to put an RSS feed of my SitePoint Blog, The Fuse, on your site, you would formulate an HTTP call that would look like this:

首先,让我们看一下CFHTTP。 CFHTTP的最常见用途是从另一个页面或站点检索数据。 例如,如果要在站点上放置我的SitePoint博客The Fuse的RSS提要,则可以制定一个HTTP调用,如下所示:

<cfhttp url="https://www.sitepoint.com/blog.rdf?blogid=7" method="get" timeout="5">

First, you want to specify the URL of the blog with the url attribute, of course. The method we’re using is "GET", and we specify that we want a five second timeout. This way, if the server is slow, it will timeout, and not hold up our application unnecessarily. The cfhttp tag returns a structure to us called cfhttp and it contains several variables that may be of use to us. First, we have the FileContent variable. This holds all the data returned to us by the URL we called. So when we display a raw text dump of CFHTTP.FileContent, we see the raw XML that is returned from the blog’s RSS feed:

首先,您当然要使用url属性指定博客的url 。 我们使用的method是“ GET”,并且我们指定要五秒钟的timeout 。 这样,如果服务器运行缓慢,它将超时,并且不会不必要地阻止我们的应用程序。 cfhttp标记将一个称为cfhttp的结构返回给我们,它包含几个可能对我们有用的变量。 首先,我们有FileContent变量。 这将保存我们调用的URL返回给我们的所有数据。 因此,当我们显示CFHTTP.FileContent的原始文本转储时,我们会看到从博客的RSS feed中返回的原始XML:

<cfoutput>#HTMLCodeFormat(cfhttp.FileContent)#</cfoutput>

Other variables returned by cfhttp are MimeType, Header, and ResponseHeader. ResponseHeader is a struct that contains several variables dealing with the response received from the URL. If we had attempted to access a binary file, such as a .jpg or .gif file, on a server somewhere, the MimeType would have been something like "image/jpeg" or "image/gif". You can perform a simple text dump of the cfhttp struct like this:

通过返回的其他变量cfhttp是MimeType , Header和ResponseHeader 。 ResponseHeader是一个结构,其中包含几个处理从URL接收到的响应的变量。 如果我们试图访问服务器上某处的二进制文件(例如.jpg或.gif文件),则MimeType应该类似于“ image / jpeg”或“ image / gif”。 您可以像这样对cfhttp结构执行简单的文本转储:

<cfdump var="#cfhttp#">

This works on ColdFusion 5 and up, and it will show you exactly what comes back when you use this particular tag.

此功能可在ColdFusion 5及更高版本上使用,并且将确切显示使用此特定标签时返回的内容。

You can also have ColdFusion automatically save the file to the server when it gets the information back from the URL, by passing it both the path and the file attributes like this:

您还可以让ColdFusion在从URL获取信息时自动将文件保存到服务器,方法是将path和file属性都传递给它,如下所示:

<cfhttp url="https://www.sitepoint.com/blog.rdf?blogid=7"  method="get"  timeout="5"  path="C:temp" filename="thefuse.rdf">

This will save the file directly to the server so that you can use it later. For example, if you didn’t want to access SitePoint’s server every time the RSS feed was displayed on your site, you could cache the file on your server using the code above, then implement some logic that would refresh the cached copy every day. It might look something like this:

这会将文件直接保存到服务器,以便以后使用。 例如,如果您不想每次在站点上显示RSS feed时都访问SitePoint的服务器,则可以使用上面的代码在服务器上缓存文件,然后实施一些逻辑来每天刷新缓存的副本。 它可能看起来像这样:

<cfdirectory action="list" directory="C:temp"   name="TheFuseCache"   filter="thefuse.rdf"> <cfif TheFuseCache.RecordCount eq 0   or DateDiff("d", TheFuseCache.DateLastModified, Now()) gt 1>  <!--- use the CFHTTP call as you see above and then do this:--->  <cfset TheFuse = cfhttp.FileContent> <cfelse>  <cffile action="read"   file="C:tempthefuse.rdf"   variable="TheFuse"> </cfif>

Now you’ve got the RSS feed updated once a day and you only have to make one call per day to SitePoint’s server (which will reduce their bandwidth costs and yours, ease the load on their server, and free up their resources to provide you with more excellent ColdFusion content!). Everyone wins!

现在,您已经每天更新一次RSS feed,而您每天只需要打一次SitePoint的服务器(这将减少它们和您的带宽成本,减轻他们服务器的负载,并释放他们的资源来为您提供服务具有更出色的ColdFusion内容!)。 每个人都赢了!

Another attribute worth mentioning with regards to cfhttp is the ResolveUrl attribute. If you used cfhttp to call a site that had relative paths in its image sources, links or style sheets, you might want to set the ResolveUrl attribute to "yes". This makes sure that all the links still point to the correct path or URL when you get the file content back. Otherwise, you’ll have broken links, style sheets, images, and the like if you try to reuse the raw HTML on your own site.

另一个属性值得问候提cfhttp是ResolveUrl属性。 如果使用cfhttp来调用在其图像源,链接或样式表中具有相对路径的站点,则可能需要将ResolveUrl属性设置为“ yes”。 这样可以确保当您取回文件内容时,所有链接仍指向正确的路径或URL。 否则,如果您尝试在自己的网站上重用原始HTML,则链接,样式表,图像等将损坏。

Now, let’s talk about cfhttpparam. This allows you to specify a parameter to send to the URL in the url attribute of the cfhttp tag. This tag lets you simulate HTML form submissions by adding parameters – GET and POST variables, cookies, and more – to your HTTP request. Let’s see this in action.

现在,让我们谈谈cfhttpparam 。 这使您可以在cfhttp标签的url属性中指定要发送到URL的参数。 通过此标签,您可以通过向HTTP请求中添加参数(例如GET和POST变量,Cookie等)来模拟HTML表单提交。 让我们来看看实际情况。

In this example, we’ll set a form variable, a cookie, a URL (query string) variable, and a file upload using our HTTP parameter tag. We’ll also send a file for the target to upload. If you try this code out on your own server, you’ll want to replace "www.example.com" with the path to your server.

在此示例中,我们将使用HTTP参数标签设置表单变量,cookie,URL(查询字符串)变量和文件上传。 我们还将发送文件供目标上载。 如果您在自己的服务器上尝试使用此代码,则需要用服务器的路径替换“ www.example.com”。

<cfif not isDefined("Form.aFormField")>  <!--- this file (receive.cfm) requests itself --->    <cfhttp url="http://127.0.0.1/receive.cfm" method="post" timeout="10">       <cfhttpparam name="aFormField" type="FormField" value="I'm in a form.">       <cfhttpparam name="aCookie" type="Cookie" value="I'm a Cookie">       <cfhttpparam name="aUrlField" type="URL" value="I'm a URL variable">       <cfhttpparam name="aFile" type="File" file="C:temptest.txt">    </cfhttp>    <cfoutput>       Here is what the server said:<br />       #cfhttp.filecontent#<br />       #cfhttp.mimetype#<br />    </cfoutput>    <!--- end of the request --->   <cfelse>    <!--- receives the variables --->    <cfoutput>       <cfif isDefined("Form.aFormField")>          Form Field: #form.aFormField#<br />       </cfif>       <cfif isDefined("Cookie.aCookie")>          Cookie Variable: #Cookie.aCookie#<br />       </cfif>       <cfif isDefined("URL.aUrlField")>          URL Variable: #URL.aUrlField#<br />       </cfif>       <cfif isDefined("Form.aFile")>          <cffile action="upload" filefield="aFile" destination="C:tempnew_test.txt" nameconflict="makeunique">       </cfif>    </cfoutput>    <!--- end of the receipt --->   </cfif>

What output is generated when you run this? Well, first the script requests itself using cfhttpparam to send some request parameters. When it is requested with those parameters, the script lists the parameters that it was sent. This output gets put into the cfhttp.FileContent variable back in the script that performed the request. It is then displayed along with the cfhttp.MimeType.

运行此命令会生成什么输出? 好吧,首先脚本使用cfhttpparam请求自身以发送一些请求参数。 当请求带有这些参数的脚本时,该脚本将列出已发送的参数。 此输出将返回执行请求的脚本中的cfhttp.FileContent变量中。 然后将其与cfhttp.MimeType一起显示。

As you can see, cfhttp and cfhttpparam provide you a great deal of flexibility over your applications, and they can help you manipulate your ColdFusion scripts to behave like real people surfing a Website. I’m sure that you can probably think of a thousand different uses for these tags.

正如你所看到的, cfhttp和cfhttpparam为您提供了极大的灵活性的交易在你的应用程序,他们可以帮助你处理你的ColdFusion脚本表现得像真正的人上网网站。 我相信您可能会想到这些标记有千种不同的用途。

I should warn you, though, that you’ll want to do plenty of error handling when using these tags. If the server you’re calling is down, you’ll need to allow your script to continue seamlessly (or at least fail gracefully). Any information for which you rely on that server will not be available. Also, use good judgment when using these tags. Making many HTTP calls will certainly cause problems on your site and could slow your server down considerably if you’re not judicious.

不过,我应该警告您,使用这些标签时,您将需要做大量的错误处理。 如果要调用的服务器已关闭,则需要允许脚本无缝地继续运行(或至少正常运行失败)。 您依赖该服务器的任何信息将不可用。 另外,在使用这些标签时,请务必做出正确的判断。 进行许多HTTP调用肯定会在您的站点上引起问题,并且如果您不明智的话,可能会大大降低服务器的速度。

Be aware that you must specify the absolute URL. If you try to specify just the relative filename, it will not resolve, and you’ll get a connection failure.

请注意,您必须指定绝对URL。 如果尝试仅指定相对文件名,它将无法解析,并且将导致连接失败。

cfheader和cfcontent标记 (cfheader and cfcontent Tags)

The next thing we should discuss is the use of the cfheader tag. This can be used to manually set HTTP response headers along with the contents of a page. HTTP headers are sent with every request. They describe the type of data that’s being sent back, along with various other attributes of the request. Let’s say that you recently found the SitePoint article on No-Refresh links, and you wanted to attempt to implement that in a ColdFusion application (having first given attention to any usability issues that might arise, of course, as described in that article).

我们接下来要讨论的是cfheader标记的使用。 这可用于手动设置HTTP响应标头以及页面内容。 HTTP标头随每个请求一起发送。 它们描述了要发送回的数据的类型,以及请求的其他各种属性。 假设您最近在No-Refresh链接上找到了SitePoint文章,并且想尝试在ColdFusion应用程序中实现它(首先要注意该文章中所描述的任何可能出现的可用性问题)。

Once you decide how you want to implement this, you can do so very easily in ColdFusion:

一旦决定了要实现的方式,就可以在ColdFusion中轻松实现:

<cfheader statuscode="204" statustext="No Content">

This sets the "no content" status code, which lets the browser know that there’s no need to refresh, as there is no content. You could choose to set the status code to 404 (page not found) if you wanted, or even 500 (internal server error). Any valid HTTP response code can be specified in there (I don’t know why you’d want to intentionally return a 404, though).

这将设置“无内容”状态代码,该代码使浏览器知道不需要刷新,因为没有内容。 您可以根据需要选择将状态代码设置为404(找不到页面),甚至设置为500(内部服务器错误)。 可以在此处指定任何有效的HTTP响应代码(不过,我不知道您为什么要有意返回404)。

You might also use this tag if you were setting up search engine/user friendly URLs. You could set up a 404 error handler that would decide if there was a valid page to display for the user’s request. If there was, you would set the status code to 200 (successful) and display the content. If it really was a page not found, you’d simply leave it as is, letting it return a 404, and tell the user that you couldn’t find the page. We’ll see yet another use of the cfheader tag in a moment.

如果要设置搜索引擎/用户友好的URL,则也可以使用此标记。 您可以设置一个404错误处理程序,该处理程序将决定是否有一个有效的页面可用于显示用户的请求。 如果存在,则将状态代码设置为200(成功)并显示内容。 如果确实没有找到页面,则只需将其保留原样,让它返回404,然后告诉用户您找不到该页面。 我们稍后将看到cfheader标记的另一种用法。

Note that you must set up the 404 handler as a URL handler, not a File handler. The File handler will dump out your ColdFusion code in the browser as if it were a text file.

请注意,您必须将404处理程序设置为URL处理程序, 而不是File处理程序 。 文件处理程序将在浏览器中转储您的ColdFusion代码,就好像它是文本文件一样。

To illustrate this tag a little better, I put together this little bit of code. Here’s the call.cfm file:

为了更好地说明此标签,我整理了一下代码。 这是call.cfm文件:

<a href="receive.cfm">Call</a>

It’s just one simple link to call the receiving page. In the receive.cfm page, I have code that looks like this:

这只是调用接收页面的简单链接。 在receive.cfm页面中,我有如下代码:

<cfheader statuscode="204" statustext="No Content"> <cffile action="write" file="C:Temptest.txt" output="file written successfully">

Now, run the call.cfm page and click the link. You’ll notice the status bar loads but the page remains on the call.cfm page. Open your Windows Explorer and go to C:Temp and you’ll see that the text.txt file was written with the string in the "output" attribute. So, it worked! Just be sure that you set the header before you output anything at all (if you’re returning no content, there should really be no content output to the browser in the receive.cfm file, though).

现在,运行call.cfm页面,然后单击链接。 您会注意到状态栏已加载,但该页面保留在call.cfm页面上。 打开Windows资源管理器,然后转到C:Temp ,您将看到text.txt文件是在“输出”属性中使用字符串编写的。 因此,它起作用了! 只需确保在输出所有内容之前先设置好标题(但是,如果不返回任何内容,则在receive.cfm文件中实际上应该没有内容输出到浏览器)。

Keep in mind that you’ll need to alert the user that some action has taken place and has been successfully completed — this could be done using JavaScript or DHTML. However you do it, don’t confuse your visitors.

请记住,您需要提醒用户已经采取了某些措施并已成功完成某些操作-可以使用JavaScript或DHTML来完成。 无论您做什么,都不要混淆您的访客。

Now, let’s delve into the cfcontent tag a bit before we move on to our project. This tag allows you to specify the MIME type that is returned by the file. If you output anything before the cfcontent tag, it will be ignored, just as with cfheader. You’ll actually have to use cfcontent in conjunction with cfheader to make sure it works properly. What we’re going to do with this tag is return an image in response to a request for a .cfm file. It’s very simple to do:

现在,在继续进行项目之前,让我们深入研究cfcontent标记。 该标记允许您指定文件返回的MIME类型。 如果在cfcontent标记之前输出任何内容,则它将被忽略,就像cfheader 。 实际上,您实际上必须将cfcontent与cfheader结合使用,以确保其正常工作。 我们将使用此标签做的是返回图像以响应对.cfm文件的请求。 这很简单:

<cfheader name="Content-Disposition" value="inline; filename=help.gif"> <cfcontent type="image/gif" deletefile="no" file="C:Inetpubwwwroothelp.gif">

When you run this file, you’ll see that it simply returns an image. Now create a new HTML document and insert this image tag in it:

运行此文件时,您会看到它只是返回一个图像。 现在创建一个新HTML文档,并将此图像标签插入其中:

<img src="returnimage.cfm" />

This assumes you have named your file with the cfcontent tag in it returnimage.cfm. Go to that file and you’ll see that it’s displayed right there on the page. You can return practically any file type you want. Simply specify the content disposition in the cfheader tag as shown above, and the content type (and, optionally, the name of the file to be sent from the server, and whether to delete the file) in the cfcontent tag, and you’re done. For another example of how to use cfcontent and cfheader, check out Macromedia’s Live Docs on the topic.

这是假设你有一个名为与您的文件cfcontent标签在它returnimage.cfm 。 转到该文件,您将看到它显示在页面上。 您几乎可以返回所需的任何文件类型。 只需如上所述在cfheader标记中指定内容配置,然后在cfheader标记中指定内容类型(以及(可选)要从服务器发送的文件的名称以及是否删除文件), cfcontent完成。 有关如何使用cfcontent和cfheader另一个示例,请查看有关该主题的Macromedia的实时文档 。

找点乐子 (Time for Some Fun)

Okay, so we’ve gotten through the dirty work — it’s time to have a little fun. Let’s pretend we’re building an image server and we want to track every image that’s displayed. I’m not going to go through the whole application from start to finish, but I’m going to show you how to return the images using ColdFusion, and how to track them each time they’re displayed.

好的,我们已经完成了肮脏的工作-是时候找点乐子了。 让我们假装我们正在构建图像服务器,并且想要跟踪显示的每个图像。 我不会从头到尾遍历整个应用程序,但是我将向您展示如何使用ColdFusion返回图像,以及如何在每次显示图像时对其进行跟踪。

First, we need a database table to store each image. This will be a very simple table that will hold an image identifier, the absolute path to the image, and a descriptive image name. When building a real image server you may want to include the ID of the user who uploaded it, the date and time it was uploaded, the page the image was displayed on, and any other information you may want regarding the image. You might also track the image size so that you can measure how much disk space and bandwidth each user is utilizing. But for simplicity’s sake, my measly little table looks like this:

首先,我们需要一个数据库表来存储每个图像。 这将是一个非常简单的表,其中将包含图像标识符,图像的绝对路径以及描述性图像名称。 在构建真实图像服务器时,您可能需要包括上载它的用户的ID,上载日期和时间,显示图像的页面以及与该图像有关的其他任何信息。 您还可以跟踪图像大小,以便可以测量每个用户正在使用多少磁盘空间和带宽。 但是为了简单起见,我的小桌子看起来像这样:

This table will store the full path to the image, a brief description of the image (so we can know what it is when looking at it through an administrative interface or in the database table itself), and a unique ID. I’m using SQL Server for this, but you can replicate the code in Access or MySQL pretty easily.

该表将存储图像的完整路径,图像的简要说明(因此,当通过管理界面或在数据库表本身中查看图像时,我们可以知道它是什么)以及唯一的ID。 我正在为此使用SQL Server,但是您可以轻松地在Access或MySQL中复制代码。

I also want to count every time that an image is accessed. Again, for simplicity’s sake I’m going to track only the Image ID and the date and time it was accessed. Here’s what my table looks like:

我也想计算每次访问图像的次数。 同样,为简单起见,我将仅跟踪图像ID及其访问的日期和时间。 这是我的桌子的样子:

Once you’ve created your tables, you’ll want to think about your directory structure. For our simple image server, we’re going to store our images in the /images/ directory on our server. We’ll have a page that returns the images and it will be stored under the root directory, just for this application. We’ll also have an anonymous upload page that will allow users to put images up.

创建表后,您将需要考虑目录结构。 对于简单的图像服务器,我们将图像存储在服务器上的/ images /目录中。 我们将有一个返回图像的页面,该页面将存储在此应用程序的根目录下。 我们还将有一个匿名上传页面,该页面允许用户放置图像。

We’ll start off with the upload script. Here’s what our form will look like:

我们将从上传脚本开始。 我们的表格如下所示:

<form name="upload" action="upload.cfm" enctype="multipart/form-data" method="post">   <input type="file" name="uploadFile" size="20" />     <input type="submit" value="Upload File" />   </form>

Allowing anonymous uploads does open security hazards, so it’s best to have some sort of authorization in place before allowing people to upload files. This is a simple example, though, so we’ll work with what we’ve got. Take special note of the enctype="multipart/form-data"" attribute. This is essential for uploading a file. I’ve named this page index.cfm.

允许匿名上传确实会带来安全隐患,因此最好在允许人们上传文件之前获得某种授权。 不过,这是一个简单的示例,因此我们将使用已有的内容。 请特别注意enctype="multipart/form-data""属性。这对于上传文件至关重要。我已将此页面命名为index.cfm 。

In the upload.cfm file, we first want to make sure the file name was specified. That code will look like this:

在上载upload.cfm文件中,我们首先要确保指定了文件名。 该代码将如下所示:

<cfif not isDefined("Form.uploadFile") or (isDefined("Form.uploadFile") and Form.uploadFile eq "")>  <p>      You must select a file to upload.    </p>    <cfabort>   </cfif>

I always check to make sure that the field is there, and that it’s not empty, to prevent people from directly accessing the URL and to keep them from submitting the form without uploading a file. Next, we’ll set the file name and the destination for the file:

我总是检查以确保该字段存在,并且该字段不为空,以防止人们直接访问URL并防止他们提交表单而不上传文件。 接下来,我们将设置文件名和文件目的地:

<cfset fileName = DateFormat(Now(), "yyyymmdd") & TimeFormat(Now(), "HHmmss")> <cfset destination = GetDirectoryFromPath(CGI.Path_Translated) & "images" & fileName>

The file name will be the date and time in a single, long string. The destination will be the images directory underneath the directory that the current file is in (the CGI.Path_Translated variable gives us the absolute path to the current file). Now we can upload the file to this location:

文件名将是一个长字符串中的日期和时间。 目标将是当前文件所在目录下的images目录( CGI.Path_Translated变量为我们提供了当前文件的绝对路径)。 现在我们可以将文件上传到以下位置:

<cffile action="upload"  filefield="uploadFile"      destination="#destination#"    accept="image/gif,image/jpeg"    nameconflict="makeunique">   <cfset FullFilePath = "#CFFILE.ServerDirectory##CFFILE.ServerFileName#.#CFFILE.ServerFileExt#">

Note that ColdFusion generates its own temporary filename under which to store the file until you decide what to do with it. As a result, if you output the value of Form.uploadFile to the screen, the filename extension is ".tmp". But, in the cffile struct, we get the actual file name and the file extension. Make sure that you limit the types of files that can be uploaded, using the "accept" attribute as above, and specifying GIF and JPEG images. You could also specify bitmaps and PNGs as well. Now, we'll put this in the database.

<cfquery name="InsertFile" datasource="kodefusion_mssql">  INSERT INTO Images (      ImagePath,      ImageName    )    VALUES (      '#FullFilePath#',      'ANONYMOUS USER UPLOAD'    )   </cfquery>

Here, we simply insert the full path to the image, along with a note that this was uploaded by an anonymous user. When we uploaded the file above, it didn’t have an extension, so now we need to rename it to match what was in the database. Here’s how we’ll do that:

在这里,我们只需插入图像的完整路径,并注意该图像是由匿名用户上传的。 当我们在上面上传文件时,它没有扩展名,因此现在我们需要重命名它以匹配数据库中的文件。 我们将执行以下操作:

<cfif FileExists(destination) and not FileExists(FullFilePath)>  <cffile action="rename" source="#destination#" destination="#FullFilePath#">   </cfif>

Now that the file is in the correct place, we’ll retrieve the URL to put in our <img> tag, and display it to the user. You’ll need to change the URL based on the way you’ve set up your directory structure.

现在文件已放置在正确的位置,我们将检索放置在<img>标记中的URL,并将其显示给用户。 您需要根据设置目录结构的方式来更改URL。

<cfquery name="GetFileID" datasource="kodefusion_mssql">  SELECT ID    FROM Images    WHERE ImagePath = '#FullFilePath#'   </cfquery>   <cfoutput>    Here's your URL: http://127.0.0.1/imagetracking/returnimage.cfm?ImageID=#GetFileID.ID#   </cfoutput>

The next step is to create the returnimage.cfm file. This is a pretty big chunk of code, so take a look first, then we’ll talk about it:

下一步是创建returnimage.cfm文件。 这是相当大的代码块,因此请先看一下,然后我们将讨论它:

<cfif not isDefined("URL.ImageID") or (isDefined("URL.ImageID") and not isNumeric(URL.ImageID))>  <!--- no image specified. you could return a default graphic here if you want. --->   <cfelse>    <cfquery name="GetImagePath" datasource="kodefusion_mssql">      SELECT ImagePath      FROM Images      WHERE ID = #URL.ImageID#    </cfquery>    <cfif GetImagePath.RecordCount neq 0>      <cfquery name="InsertTracking" datasource="kodefusion_mssql">        INSERT INTO ImageTracking (          ImageID,          InsertDate        )        VALUES (          #URL.ImageID#,          GetDate()        )      </cfquery>      <cfset fileExt = ListLast(GetFileFromPath(GetImagePath.ImagePath), ".")>      <cfif fileExt eq "jpg" or fileExt eq "jpeg">        <cfset contentType = "image/jpeg">      <cfelse>        <cfset contentType = "image/gif">      </cfif>      <cfheader name="Content-Disposition" value="inline; filename=#GetFileFromPath(GetImagePath.ImagePath)#">      <cfcontent type="#contentType#" deletefile="no" file="#GetImagePath.ImagePath#">    <cfelse>      <!--- no image. return default graphic. --->    </cfif>   </cfif>

The first thing we do is check to make sure there’s an image ID available. If not, we could return a default "Graphic Not Available" type of graphic. If we don’t, an infamous red X will appear there.

我们要做的第一件事是检查并确保有可用的图像ID。 如果没有,我们可以返回默认的“图形不可用”图形类型。 如果我们不这样做,那会出现一个臭名昭著的红色X。

Assuming an ID is provided, we use it to select the ImagePath field from our Images table. We check to make sure the query returned a result, and we put a row in the ImageTracking table to indicate that the image was accessed. We then figure out if this was a JPEG or a GIF image, and set the content type variable accordingly. You could create a separate "FileExtension" field in the Images table and eliminate this bit of work by storing the file extension or even the content type in there.

假设提供了ID,我们将其用于从Images表中选择ImagePath字段。 我们检查以确保查询返回了结果,然后在ImageTracking表中放置一行以指示已访问图像。 然后,我们确定这是JPEG图像还是GIF图像,并相应地设置内容类型变量。 您可以在图像表中创建一个单独的“ FileExtension”字段,并通过在其中存储文件扩展名甚至内容类型来消除此工作量。

Once we have the content type figured out, we send our cfheader, then push our image along using cfcontent. Make sure that the deletefile attribute is set to "no", so that the file isn’t removed after it’s used. If there are no images matching that ID in the database, we could return our "Image Not Available" graphic, or just let it display a red X.

确定了内容类型后,我们将发送cfheader ,然后使用cfcontent推送图像。 确保deletefile属性设置为“ no”,以便在使用文件后不会将其删除。 如果数据库中没有与该ID匹配的图像,我们可以返回“图像不可用”图形,或者只是让其显示红色的X。

Be sure to specify in the cfheader value attribute that this is inline data. This means that it will be displayed in the Web page, not downloaded as an attachment. (Hint: If you want to track downloads of a file, you could use this method and set the value attribute to "attachment".) Also, note that the value should be the file name only, not the full path.

确保在cfheader值属性中指定这是内联数据。 这意味着它将显示在网页中,而不是作为附件下载。 (提示:如果要跟踪文件的下载,则可以使用此方法,并将value属性设置为“ attachment”。)此外,请注意,该值应仅是文件名,而不是完整路径。

结论 (Conclusion)

There you have it: a very basic start on an image server. There are many, many things that you can do with the tags and techniques we’ve discussed in this article. Your assignment now is to take the above application and build it into something more comprehensive. Add a way for users to name images, a report to show how often the images are accessed, and the ability to store more data about each image upload and each time the file is accessed. There are plenty of things you can do!

到此为止:图像服务器的一个非常基本的起点。 您可以使用本文中讨论的标签和技术来做很多事情。 现在您的任务是采用上述应用程序并将其构建为更全面的内容。 添加了一种为用户命名图像的方式,一个报告以显示图像的访问频率以及可以存储有关每个图像上传和每次访问文件的更多数据的功能。 您可以做很多事情!

In this article, we’ve covered a lot of ground (and I’m pretty much exhausted, believe me!). We’ve discussed using the cfhttp tag to retrieve an RSS feed, using the cfhttpparam tag to send form, URL, and cookie variables, as well as files, to a remote Website, and how to return file types other than text and HTML, using ColdFusion. The more applications you develop, the more ways you will find to apply these tags in your code. Until next time, have fun in the wide world of ColdFusion.

在本文中,我们讨论了很多内容(相信我,我已经筋疲力尽了!)。 我们已经用讨论的cfhttp标签来获取RSS订阅源,使用cfhttpparam标签发送的形式,URL和cookie的变量,以及文件,到远程网站,以及如何返回其他文件类型不是文本和HTML,使用ColdFusion。 您开发的应用程序越多,就会发现在代码中应用这些标记的方法越多。 直到下一次,在ColdFusion的广阔世界中尽情玩乐。

翻译自: https://www.sitepoint.com/coldfusion-practical-uses-http/

coldfusion

最新回复(0)