Uploading a File in Coldfusion

AID: 2888
  • Status: Published

2100 points

I came accross many uploads in coldfusion which are quite different from each other. Although each have its own advantages and disadvantages, I prefer the one way which seems quite good to me and i almost use it myself many a times. Most of you guys may find it not upto standard but it has some features which can handle large pages.

So here is the basic Code..

Suppose we have a form with 100 fields. out of that 100 fields we have one field for upload. Now we will fill that fields and then click browse to Upload a file also and when we click Submit, we may encounter any kind of Error..

I/O Error
File Unknown Error and many others.

So our whole filling up the form goes to dump..

Now we can do it in simple way:

Suppose we want to upload an image..

now first we see that if that image already exists, if yes we will display it like this:

<cfif headerLogo IS NOT "">
    <tr>
      <td class="middleright"><strong>Previous Image:</strong></td>
      <td><cfoutput><img src="headers/#headerLogo#" border="0" /></cfoutput></td>
    </tr>
    </cfif>
  <tr>
    <td class="middleright"><strong>Header Logo:</strong></td>
    <td><cfinput type="text" name="headerLogo" id="headerLogo" tabindex="3" class="inputstyle" value="#headerLogo#">&nbsp;&nbsp;<a href="javascript:void(0);" onClick="WinOpen('upload.cfm','400','300');">Add Image</a></td>
  </tr>

now if the headerLogo is not defined, or it does not exists, we will use the following cfinput tag which have an ADD iMAGE button located next to it which will open the POPUP Window and we will be doing the upload there..

Javascript we used is this:

function WinOpen(url,x,y) {
        var attributes = "toolbar=no,scrollbars=yes,resizable=no,width=" + x + ",height=" + y;
        msgWindow=window.open(url,"WinOpen",attributes);
}
if ( !WinOpen ){
    alert('You must disable your popup blocker for this website to allow you to login!');
}

Now we have one JS File which check for the file upload extention and that is below:
function checkFileUpload(form, extensions, requireUpload, sizeLimit, minWidth, minHeight, maxWidth, maxHeight, saveWidth, saveHeight) {
	var allUploadsOK = true;
	document.MM_returnValue = false;
	for (var i = 0; i < form.elements.length; i++) {
		field = form.elements[i];
		if (!field.type || field.type.toUpperCase() != 'FILE') {
			continue;
		}
		checkOneFileUpload(field,extensions,requireUpload,sizeLimit,minWidth,minHeight,maxWidth,maxHeight,saveWidth,saveHeight);
		if (!field.uploadOK) {
			allUploadsOK = false;
			break;
		}
	}
	if (allUploadsOK) {
		document.MM_returnValue = true;
	}
}

function checkOneFileUpload(field, extensions, requireUpload, sizeLimit, minWidth, minHeight, maxWidth, maxHeight, saveWidth, saveHeight) {
	var fileName = field.value.replace(/"/gi,'');
	field.uploadOK = false;
	if (fileName == '') {
		if (requireUpload) {
			alert('File is required!');
			field.focus();
			return;
		} else {
			field.uploadOK = true;
		}
	} else {
		if (extensions != '') {
			checkFileExtension(field, fileName, extensions);
		} else {
			field.uploadOK = true;
		}
		if (!document.layers && field.uploadOK) {  
			document.PU_uploadForm = field.form;
			re = new RegExp("\.(gif|jpg|png|bmp|jpeg)$","i");
			if(re.test(fileName)) { // && (sizeLimit != '' || minWidth != '' || minHeight != '' || maxWidth != '' || maxHeight != '' || saveWidth != '' || saveHeight != '')) {
				checkImageDimensions(field,sizeLimit,minWidth,minHeight,maxWidth,maxHeight,saveWidth,saveHeight);
			}
		}
	}
	return;
}
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:

Select allOpen in new window


Now next we will see our UPLOAD.CFM Page
<cfform ACTION="uploading.cfm" METHOD="post" enctype="multipart/form-data" name="imageA" id="imageA" onSubmit="checkFileUpload(this,'GIF,JPG,JPEG,BMP,PNG',true,'','','','','','','');return document.MM_returnValue">
  <table width="100%" border="0" cellpadding="1" cellspacing="2" class="tableborder">
    <tr valign="baseline">
      <td colspan="2" align="center" nowrap class="botpreview">Upload Image(s)</td>
    </tr>
    <cfif headerLogo IS NOT "">
    <tr valign="baseline">
      <td align="right" nowrap>&nbsp;</td>
      <td>Previous Image:</td>
    </tr>
    <tr valign="baseline">
      <td align="right" nowrap>&nbsp;</td>
      <td><cfoutput><img src="headers/#headerLogo#" border="0" /></cfoutput></td>
    </tr>
    </cfif>
    <tr valign="baseline"> 
      <td width="4%" align="right" nowrap>&nbsp;</td>
      <td width="96%"> Upload Image:</td>
    </tr>
    <tr valign="baseline"> 
      <td nowrap align="right" height="28">&nbsp;</td>
      <td height="28"> <input name="ImageFile" type="file" class="inputstyle" tabindex="1" onChange="checkOneFileUpload(this,'GIF,JPG,JPEG,BMP,PNG',true,'','','','','','','')"> </td>
    </tr>
    <tr valign="baseline">
      <td>&nbsp;</td>
      <td>Upload Size:</td>
    </tr>
    <tr valign="baseline">
      <td>&nbsp;</td>
      <td><select name="uploadsize" class="inputstyle" id="uploadsize" tabindex="2">
      	<option value="100">100</option>
        <option value="125">125</option>
        <option value="150">150</option>
        <option value="175">175</option>
        <option value="200">200</option>
      </select>
        <br />
        (* This is the width of the Image, the Height will be automatically be resized base upon on selection of width)</td>
    </tr>
    <tr valign="baseline"> 
      <td nowrap align="right"></td>
      <td> <input name="submit" type="submit" class="tinyborder" value="Upload Image" tabindex="3"> 
      </td>
    </tr>
  </table>
</cfform>
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:

Select allOpen in new window


Now Action Page:
<cfset filter = "image/jpg,image/jpeg,image/png,image/pjpeg,image/bmp">
<cfset files = "jpg,bmp,jpeg,pjpeg,bmp,png">
<cfif StructKeyExists(FORM,'submit')>
<cftry>
	<cfif IsDefined('form.ImageFile') AND form.ImageFile IS "">
    	<cfset n = "Error! Please Upload a File">
    <cfelse>
    	  <cfset NewDirectory = "headers">
		  <cfset destination = ExpandPath("#NewDirectory#")>
		  <cfset TAB = Chr(9)>
		  <cfif NOT DirectoryExists(destination)>
             <cfdirectory action="create" directory="#destination#" mode="777">
           </cfif>
          <cffile action="upload" accept="#filter#" filefield="ImageFile" destination="#destination#\" nameconflict="makeunique">
          <cfset uploadfile = #cffile.ServerFile#>
          <cfimage action="resize" source="#destination#\#uploadfile#" destination="#destination#\#uploadfile#" 
          overwrite="yes" width="#form.uploadsize#" height="">
		  <cfset form.uploadfile = "#uploadfile#">
          <cfif FileExists("#ExpandPath("headers\#form.headerLogo#")#")>
          		<cffile action="delete" file="#ExpandPath("headers\#form.headerLogo#")#">
          </cfif>
          <cfif not StructKeyExists(FORM,'mainID')>
          	we do the addition in the database here
          </cfif>
          <cfset n = "#trim(str)#">
    </cfif>        
<cfcatch>
<cfset n = "Error! #cfcatch.Detail# #cfcatch.Message#">
</cfcatch>
</cftry>
<cflocation addtoken="no" url="closex.cfm?n=#ToBase64(n)#">
</cfif>
                                    
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:

Select allOpen in new window


now in closex.cfm we do the following:

<tr>
          <td width="15%" align="left"><cfif refindnocase('error',#ToString(ToBinary(n))#)>
              <a href="javascript:void(0);" onclick="window.history.back(-2);">Go Back</a>
              <cfelse>
            </cfif></td>
          <td width="85%" align="right"><cfoutput> <a href="javascript:void(0);" onclick="self.opener.location.href='header.cfm'; window.close(); return false;">Close Window</a> </cfoutput></td>
        </tr>

a notification is displayed and parent page is refreshed and image is uploaded and now you can go through the form fields filling up!

There is lot more that can be done to enhance this tute! Many options still await like watermark, shadow and much much more!

So keep Coding and Happy Coding..

Please contact me for any Updates on the issue!
Asked On
2010-04-17 at 05:21:05ID2888
Tags

Coldfusion

,

cfmx

,

cfc

,

Components

Topic

ColdFusion Application Server

Views
1571

Add your Comment

Please Sign up or Log in to comment on this article.

Join Experts Exchange Today

Gain Access to all our Tech Resources

Get personalized answers

Ask unlimited questions

Access Proven Solutions

Search 3.2 million solutions

Read In-Depth How-To Guides

1000+ articles, demos, & tips

Watch Step by Step Tutorials

Learn direct from top tech pros

And Much More!

Your complete tech resource

See Plans and Pricing

30-day free trial. Register in 60 seconds.

Loading Advertisement...

Top ColdFusion Server Experts

  1. Zvonko

    2,800

    0 points yesterday

    Profile
    Rank: Genius
  2. srikanthmadishetti

    2,580

    20 points yesterday

    Profile
    Rank: Guru
  3. digicidal

    2,000

    0 points yesterday

    Profile
    Rank: Guru
  4. maestropsm

    1,600

    0 points yesterday

    Profile
    Rank: Guru
  5. _agx_

    1,268

    0 points yesterday

    Profile
    Rank: Genius
  6. gdemaria

    1,064

    0 points yesterday

    Profile
    Rank: Genius
  7. brijeshchauhan

    668

    0 points yesterday

    Profile
    Rank: Guru
  8. myselfrandhawa

    250

    10 points yesterday

    Profile
    Rank: Guru

Hall Of Fame