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 <cffile>
tag.
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 you need to ensure that you have enctype="multipart/form-data"
within the form tag, and that you use method="post"
.
The Destination
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.
Name Conflicts
If there's already a file of the same name, the above code will fail. Fortunately, the <cffile>
tag has an attribute called nameConflict
. The 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:
error
- An error is thrown.
skip
- The file is not uploaded.
overwrite
- The file on the server is overwritten with the new one.
makeunique
- 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.
Other Attributes
You can also supply the following (optional) attributes to the <cffile>
tag.
mode
- Allows you to set permissions on Unix platforms.
attributes
- Allows you to specify whether the file should be read only, hidden, or normal.