ColdFusion Upload File
You can use ColdFusion's
<cffile> tag to upload a file to the server.
To allow users to upload a file to the server, you first need to provide a form for them to specify which file they want to upload. Once they click the submit button of the form, the action page is called. This is the page that needs to contain the
Example of Uploading a File to the Server
The following code creates a form, then if the form has been submitted, uploads the file. By only supplying a directory name for the destination, the original file name will be intact. If we wanted to change it, we could specify another file name.
Also note that I specified
method="post" within the HTML
The value you provide for the
destination attribute is the location that the file will be uploaded to. This is a required field.
This can be an absolute path (starting with a drive letter and a colon, or a forward or backward slash) or a relative path. If relative, it is relative to the ColdFusion temporary directory. You can use the
GetTempDirectory function to find the temporary directory. You may also see the temp directory returned in error messages with your file upload.
If the destination you specify does not exist, ColdFusion creates a file with the specified destination name.
If there's already a file of the same name, the above code will fail. Fortunately, the
<cffile> tag has an attribute called
nameConflict attribute allows you to determine what to do if there's a file with the same name already on the server.
Possible values for the
nameConflict attribute are:
- An error is thrown.
- The file is not saved.
- The file on the server is overwritten with the new one.
- ColdFusion assigns the new file with a new name.
Restricting File Types
If you only want your users to be able to upload certain file types, you can use the
accept attribute. This allows you to provide a comma separated list of file types that are allowed to be uploaded. For example,
accept="image/jpg,image/gif,image/png" will only allow GIFs, JPGs, and PNG images to be uploaded.
You can also use
allowedExtensions to restrict by file extension.
Here's the full syntax of
ColdFusion also has a
cffileupload tag, which displays a dialog for uploading multiple files from the user's system. See Adobe's documentation for
cffileupload for more information.