|
Uploading an image and previewing the thumbnail in one hit |
A recent piece of functionality required a user to be able to upload an image, and view a thumbnail of that image alongside all the other related details that they were entering (item specific data etc).
After having a look through several forums it seemed that people's opinions were split on whether this could be accomplished using Ajax at all. So I decided to go old school and use an iFrame. I'm not a big fan of frames in any incarnation, but in this case I was willing to make an exception.
So firstly there is an upload form. It is a pretty standard ColdFusion form. Just remember when uploading a file to set the enctype="multipart/form-data". Also the submit button does not submit the form, it fires a JavaScript function 'changeFrame()'. The JavaScript function sets the target of the form submission to the iFrame, and then submits it.
2 <iframe id="uploadFrame" name="uploadFrame" src="action.cfm" height="110" width="90" scrolling="no" frameborder="0"></iframe>
3
4<form name="uploader" action="action.cfm" method="post" enctype="multipart/form-data">
5 <input type="file" name="image" size="5">
6 <input type="button" name="action" value="Upload" onclick="changeFrame()"/>
7 </form>
8</div>
9
10<s/cript>
11function changeFrame()
12 {
13 document.getElementById('uploader').target = 'uploadFrame';
14 document.getElementById('uploader').submit();
15 }
16</s/cript>
The form submits to the 'action.cfm' template. This template displays a placeholder image thumbnail initially, but when the form is submitted it performs the file upload using cffile, then displays the newly uploaded file instead of the placeholder. Ideally at this point I would like to resize the image with cfimage, but my hosting company is still using ColdFusion 7, so I may have to use a third party tag to do the same.
2<cfset dest = "webroot/root/tmp/">
3
4<cfif isdefined('form.image')>
5 <cffile action="upload" filefield="form.image" destination="#dest#" nameconflict="makeunique">
6 <cfset variables.img = cffile.clientFile>
7<cfelse>
8 <cfset variables.img = "holder.gif">
9
10</cfif>
11
12<cfoutput><img src="tmp\#variables.img#" height="100" width="75" border="1"></cfoutput>
13</body>
It is a shame I had to use an iFrame, and it would be really interesting to see if this is possible in a more web 2.0 scripted way.
For resizing check out image.cfc by Rick Root.