|
Handling CFfile upload 'accept' file type errors |
I was working on a system recently that allowed a user to upload images onto the server. It was restricted to files types of images, more specifically 'jpeg' and 'gif' files.
This is easily done with the 'accept' parameter, as documented in the ColdFusion documentation:
2
3Limits the MIME types to accept. Comma-delimited list. For example, the following code permits JPEG and Microsoft Word file uploads:
4accept = "image/jpg, application/msword"
5
6The browser uses the file extension to determine file type.
It is important to note here that it is the browser uses the file extension, so renaming an exe to jpg would fool it entirely.
Issues arise when you don't handle an invalid file upload in a friendly manner. In this case when a user tried to upload an incorrect file type they saw a nasty unformatted error message stating that the request could not be processed as the file was the wrong Mime type.
You cannot tell what the file type is until you attempt to upload it, so wrap your cffile tags in a simple try-catch and handle any errors in the same fashion as you normally would, I.E. by handling the system message and instead displaying a nice, user friendly message that doesn't sound like it was written by robots.
2
3<cffile action="upload" destination="#request.uploadPath#" fileField="form.new_image" accept="image/jpeg, image/gif" nameConflict="overwrite">
4
5<cfcatch>
6
7 <cfset attributes.errors.type = 'error'>
8 <cfset attributes.errors.message = "The type of file you have tried to upload is not allowed, please select a jpg or gif.">
9 <cfset request.continue = false>
10
11</cfcatch>
12
13</cftry>
cfif FindNoCase("not accepted", cfcatch.Message).
Since there are some known issues with the accept attribute of cffile (which are in fact browser issues - Firefox needs "application/upload" for .PDF's, IE expects its own jpeg mime type) and it can be fooled easily by renaming the file extension, I prefer checking the extension myself. That doesn't make it more secure, but easier to implement.
Andreas Schuldhaus
That's a good tip, I was more surprised to find that you can't do much pre-processing on the file before you try the upload.
You are right tho, its is very easy to spoof the file type, so you shouldn't just rely on the extension to validate it.
http://www.coldfusionjedi.com/index.cfm/2007/10/12...
I've also been adding functions like isPDF(), isImage() & isXML() to verify whether the uploaded files can be read correctly by ColdFusion in case the scripts need to modify them later (read, resize, watermark).
That is a good article by Ray, he goes into the process quite a lot there.
That's quite a good idea having a library of validators to check the files more thoroughly. You could almost run a pre upload routine where the file was uploaded into a secure location, validated and then just moved.
Using accept="image/*" seems to validate all image mime types.