A Better Approach to Securely Upload Your Files to the Directory using Coldfusion

we will split this tutorial in few Parts like this!

1. Create a Upload Form
2. Upload a File
    2.1 Check to See if Uploading Image is not too Big in size, we will try here to make a check through javascript & server side.
    2.2 Check to See if the Image size is not extensibly large.
3. Change the Extension of the JPEG for rendering easily in the webpage and with less Processing time.
4. Resize the Image If required (Optional)
5. Let's Also Include the Watermark Option to watermark the JPEG Image (Optional)
6. Redirect to the User to the End Page to View the Uploaded Image
7. End of the Tutorial!

Let's now begin with our Part-1 Link!

<html>
<head>
<title>Welcome to Upload Functionality</title>
<script language="javascript">
function LimitAttach(form, file) {
    extArray = new Array(".jpg",".png",".gif",".bmp",".tiff",".pct",".pcd");
    allowSubmit = false;
    if (!file) return;
    while (file.indexOf("\\") != -1)
    file = file.slice(file.indexOf("\\") + 1);
    ext = file.slice(file.indexOf(".")).toLowerCase();
    for (var i = 0; i < extArray.length; i++) {
    if (extArray[i] == ext) { allowSubmit = true; break; }
    }
    if (allowSubmit) return true;
    else
    alert("Please only upload files that end in types:  "
    + (extArray.join("  ")) + "\nPlease select a new "
    + "file to upload and submit again.");
    return false;
}
</script>
</head>
<body>
<form method="post" action="upload.cfm" enctype="multipart/form-data">
<table align="left" width="410">
<tr><td>
    <input type="file" name="uploadfile" id="uploadfile" tabindex="1">
</td></tr>
<tr><td>
    <select name="checkforoptions" id="checkforoptions">
 <option value="none">(Select One)...</option>
 <option value="1">Resize {800^600}</option>
 <option value="2">Watermark</option>
    </select>
<tr><td>
    <input type="submit" name="createupload" id="createupload" tabindex="2" value="Create New Upload"  onclick='return LimitAttach(this.form, this.form.uploadfile.value)'>
</td></tr>
</table>
</form>
</body>
</html>

Let's now begin with our Part-2 Link!  The Page is Called as <Upload.cfm>

<cfset accept = "image/jpg,image/jpeg,image/png,image/gif,image/pjpeg,image/bmp,image/pct,image/pcd,image/tiff">
<cfset files = "jpg,bmp,jpeg,pjpeg,bmp,png,gif,tiff,pct,pcd">

<!--- Wrap Around the cftry/catch block --->
<cftry>
<cfif  structKeyExists(FORM,"createupload")>
 <!--- A Server side validation Check --->
 <cfif len(form.uploadfile) IS 0>
  <cfset n = "Error! Please Upload Image File">
 <cfelse>
  <cfset path = getDirectoryFromPath(getCurrentTemplatePath())>
  <cfscript>
  info = StructNew();
  info.directory = "uploadImages"; 
  </cfscript>
  <cfif not directoryexists(info.directory)>
   <cfdirectory action="create" name="#path##info.directory#">  
  </cfif>
  <cfset newPath = "#path##info.directory#">
  <cftry>
   <cffile action="upload" accept="#accept#" filefield="uploadfile"
   destination="#newpath#\" nameconflict="makeunique">
             <cfset uploadfile = cffile.ServerFile>
   <cfset imageName = cffile.serverfileName>
   <cfif IsImageFile("#newPath#\#uploadfile#")>
    <!--- Check if File Size is not much bigger --->
    <cfif cffile.filsesize GT 500000>
     <cffile action="delete" file="#newPath#\#uploadfile#">
    </cfif>
    <!--- Check if File width & height is not too much big. --->
    <cfset MyImage = ImageRead("#newPath#\#uploadfile#")>
    <cfset info = ImageInfo(MyImage)>
    <cfif info.width GT 2048 AND info.height GT 2048>
     <cffile action="delete" file="#newPath#\#uploadfile#"> 
    </cfif>
    <!--- Now we have Checked the Details we need, Now we will go ahead and Convert the file if needed. --->
    <cfif cffile.serverfileext IS 'jpg'>
    <cfelse>
    <cfimage action="convert"
    source="#MyImage#" destination="#newPath#\#imageName#.jpg" overwrite="true">
    <cfset MyImage = #imageName#.jpg>
    </cfif>

    <! --- Now we are in the process of Resizing the Image before we Proceed Furthur, This is Optional, So we can Skip That if the Value is not defined in the  HTML Form--->
    <cfif isDefined('form.checkforoptions') AND form.checkforoptions EQ 1>
     <cfset imageResize(MyImage,"800","600")>
     <cfset ImageWrite(myImage,"#newPath#\")>
    <cfelseif isDefined('form.checkforoptions') AND form.checkforoptions EQ 2>
     <cfset Watermark = ImageNew("",100,20,"rgb","##F0F0F0")>
     <cfset ImageSetDrawingColor(watermark,"##666666")>
     <cfset ImageDrawRect(Watermark,0,0,
     (Watermark.GetWidth() - 1),(Watermark.GetHeight() - 1))>
     <cfset ImageSetAntialiasing(watermark,"on")>
     <cfset setAttr = {Font="verdana",size="5",style="italic"}>
     <cfset ImageDrawText(Watermark,"Gavy Randhawa",11,14,setAttr)>
     <cfset ImageSetDrawingTransparency(MyImage,50)>
     <cfset ImagePaste(MyImage,Watermark,(MyImage.GetWidth()-watermark.GetWidth() - 3),(MyImage.GetHeight()-watermark.GetHeight() - 3))>
     <cfset ImageWrite(myImage,"#newPath#\")>
    </cfif>
    <cflocation="thanks.cfm?img=#tobase64(MyImage)#" addtoken="no">
   </cfif> 
  <cfcatch>
   <cfset n = "Error! Unhandled Exception Occurred, reverting back">
   <cfif fileExists("#newPath#\#uploadfile#")>
    <cffile action="delete" file="#newPath#\#uploadfile#">
   </cfif>
  </cfcatch>
  </cftry>
   
 </cfif>
</cfif>
<cfcatch type="any">
<cfset n = "Error! #cfcatch.detail# #cfcatch.message#">
</cfcatch>
</cftry>

Now Our Thanks.cfm Page, We are Passing The Image Name in a Url So we need just a Path to Find the image and Show to the User

<html>
<head>
<title>Hello! The Upload ha been a Success</title>
</head>
<body>
<table align="center" width="70%">
<tr><td>Uploaded Image</td></tr>
<tr><td>
<cfif isDefined('url.img')>
 <img src="UploadImages/#ToString(ToBinary(url.img))#" border="0"/>
<cfelse>
 <div align="center">Warning! You landed this Page without any Uploading, This is a Wrong Page Instead</div>
</cfif>
</td></tr>
</table>
</body>
</html>

End of the Tutorial

About This Tutorial
Author: Gurpreet Singh Randhawa
Skill Level: Beginner 
 
 
 
Platforms Tested: CF8,CF9,Railo
Total Views: 58,245
Submission Date: July 09, 2011
Last Update Date: July 09, 2011
All Tutorials By This Autor: 9
Discuss This Tutorial
Advertisement


Website Designed and Developed by Pablo Varando.