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".
<cfif isDefined("fileUpload")>
<cffile action="upload"
fileField="fileUpload"
destination="C:\docs">
<p>Thankyou, your file has been uploaded.</p>
</cfif>
<form enctype="multipart/form-data" method="post">
<input type="file" name="fileUpload" /><br />
<input type="submit" value="Upload File" />
</form>
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.
