Showing an image after upload
In many cases, we upload images, so I want to show how to display the uploaded image right there in the flash form. Right now, we can only load jpgs.
In the simplest case, the file name of the picture will be the same when it gets uploaded. So in order to show it, when only need the original file name.
Besides the file upload controls, we have a couple of additional controls:
<cfformitem type="html" height="300" width="700"
bind="<p><img src='{myform.picture}'></p>"></cfformitem>
<cfinput type="hidden" name="picture"/>
then, in the onComplete function, we set the picture to the newly uploaded file:
//some shorcuts to our controls
var fileNameField = fileNameField;
var myform = myform;
uploadListener.onComplete = function(){
//show the picture
myform.picture = fileNameField.text;
}
fileNameField is the text field where we showed the name of the file to be uploaded. We assume that this field hasn’t changed since the user pressed upload and the upload was completed. We can prevent it from changing by disabling the choose button until the file has uploaded successfully or some other event (error, cancel, etc) happens.
I personally almost never use the filename that the user gives me because they usually contain spaces. So I change the file name when it gets uploaded. But that means that the form will not know what the new name is, and therefore it won’t be able to show it. To get around that, we can set the filename before hand, say the item id, or similar, and then pass that by query string to the upload action page. In that way, we can assume that the action page gave that filename to the uploaded file. You can view an example of that in the source download.
A live example
Download the source
Related posts:
File Upload with ColdFusion Flash Forms
File upload explained and expanded
felipe
I have a cftree that shows the folders in the server in the same form i alredy managed to pass the value of the selected folder in the tree to the upload.cfm. I would like now to add a node to the tree inside that folder with the filename after it gets uploaded, any sugestion?
Todd
Nahuel
Here you have :)
http://www.asfusion.com/blog/entry/detecting-flash-player-8-on-a-cfform
Marcos Placona
Rick
felipe
Gavin Dority
uploadListener.onComplete = function()
{
output.text = "Upload complete";
getURL("javascript:alert('Test Call');");
}
Todd
No need for a javascript call. Just use an actionscript alert.
alert("test call");
Joseph Wylie
Anyone know how to achieve this?
Thanks
James Spivey
Laura
You cannot have the code for cfgraph inside cfform. It will not show, as you have already found out. You either need to create the image/swf, save it and then put it in the cfformitem=html by <img src="mychart.jpg"> or generate it in a page that returns the binary data and put it in the form the same way. I believe Ray Camden has an example of that.
http://ray.camdenfamily.com/index.cfm/2005/7/23/Embedded-CFCHART-in-Flash-Forms--Part-3
Felipe and Joseph
You cannot manipulate the filedata (and get a file the user hasn't chosen) nor grab am arbitrary file from the client machine and send it. Don't you think that would be pretty insecure, Flash just grabbing files from your hard drive and uploading them?
James,
In my example, I generate a random number, you can replace that with your session.loggedIn.m_id variable in the hidden field called id at line 144.
<cfinput type="hidden" name="id" value="#SESSION.LoggedIn.M_ID)#" />
if you leave everything else the same, then your upload action page will get a variable called url.id with the session id you have set in the previous page.
Frank D'Elia
Rick
<FORM ACTION="upload.cfm" ENCTYPE="multipart/form-data" METHOD="POST">
<INPUT TYPE="file" NAME="Filedata"><input type="submit">
</FORM>
run and see what error you get on your upload page, solve the problem and when you try your real app you should not get error 500 anymore.
J. Asher Gilbert - Zealio
Also, is I cancel the file dialog but then choose to 'browse...' again, all the listeners fire twice on each event. The listeners fire as many times as you've had the browse dialog open.
This needs to be improved.
Great job though
Asher Gilbert
Hope this helps...
<cfsavecontent variable="browseScript">
progressBarBackground.width = 255;
var uploadSwf = textArea.label.upload;
var panelInfo = panelInfo;
var output = output;
var uploadListener = {};
var totalWidth = progressBarBackground.width;
var fileNameField = fileNameField;
var progressBar = progressBar;
var uploadBtn = uploadBtn;
var cancelBtn = cancelBtn;
var maxSize;
uploadSwf.addListener(uploadListener);
uploadSwf.browse([{description: "Image Files (jpg only)", extension: "*.jpg;"}]);
//this statement, checks to see that the .swf file providing the upload features of the form
//has loaded, and makes sure that the listener has not already been created...
//That way these events are not created every single time the browse button is clicked, so I can now use alerts()
//inside the events, with out the risk of the the alert duplicating...
if(uploadSwf.browse != undefined && _global.bCreatedListener == undefined){
_global.bCreatedListener = true;
_global.MathNumberParse= function(n)
{
return (n >> 0)+"."+ (Math.round(n*100)%100);
}
-------
LISTENER EVENTS CHOPPED OUT HERE TO SAVE SPACE ON THIS POST
-------
}
}
</cfsavecontent>
George Smith
Steven Ross
thanks,
Steven
Nahuel
I uploaded the source.
http://www.asfusion.com/blog/files/cfforms/fileupload.fla
Actually it's very simple I just have this code on the first frame:
import flash.net.FileReference;
var imageFile:FileReference = new FileReference();
function addListener(listener:Object):Void
{
imageFile.addListener(listener);
}
function browse(list:Array):Void
{
imageFile.browse(list);
}
function upload( path:String):Boolean
{
return imageFile.upload(path);
}
function cancel():Void
{
imageFile.cancel();
}
Laura
Uploading the file and submitting the form has to happen in two different steps. The upload only sends file data, nothing more (expect for anything needed that you can pass by query string).
After the upload is complete, you can submit the form with the other fields like you would normally do. What you do with data of the submitted form is up to you (update/insert db, send an email, etc)
George Smith
I was kinda thinking that though. Didnt I read in one of these posts that there could be some sort of auto submision after the image file is uploaded? my problem is that people submitting images and info that corisponds with the image can get out of sink, Images without descriptions, or descriptions without images, kinda slopppy... Thanks for your help
Laura
You could, if you wanted, to automatically submit the form after upload by adding _root.submitForm() to the onComplete function code.
What I usually do is to set up a temp directory where I upload the files. Then, when the form is submitted with the other fields, I look for the file referenced in the form and move it to its permanent directory and perhaps rename it. Anything left in the temp dir is either because the form was never submitted or people are still working on them.
If you don't want to get description without images, just check that they have uploaded something at submit and do not submit the form unless they have done so.
Just an idea.
George
Thanks for the advice but im still not getting it. I put the statement to submit after the upload in. But where should I put the <cfquery> update, statement? On another page? How does the form know where to go. I put an action="update.cfm" in the cfform but that does not seem to do anything. I can see that the form after the image is uploaded goes to the upload.cfm where the cffile action="upload" is. So where do I put the update to recieve the other form fields (input text)? Im unsure why I would want to rename and have a temp directory. Anyways thanks, your site has been very usefull.
George
I got it... 6 text fields, choose file, then upload (one submit). Sooo cool
Thanks again
Will
Thanks,
Will
Russ
Justin Cook
Thanks,
Justin
Justin Cook
<cfformitem type="html" height="225" width="400" bind="<p><img src='{myform.picture}'></p>"></cfformitem>
TO:
<cfformitem type="html" height="225" width="400" bind="<p><img src='includes\imageUploads\{myform.picture}'></p>"></cfformitem>
Or if you all have a different suggestion.
Tks,
Justin
Philip Bedi
This is really a question related to Flex, can we open a PDF file in Flex application or we need to open it in iframe?
Justin Cook
1. See my note above...the image doesn't display.
2. Won't upload in Firefox or Opera. Is this supposed to work in those two? Or could I be doing something wrong and what might that be?
Thanks in advance.
Federico García
I have a problem with the renamed method, when the upload is completed the file is not renamed. He creates a directory with the name of the variable myform.id and inside this save the file with the original name.
Since I can solve this problem?
Thank in advance.
Laura
1. Your syntax is correct. Your path might be wrong. Since you are using relative path, think that it is relative to where the form is located. Also, you probably want to use / instead of \
2. It works in Firefox and Opera unless you are doing it in a password-protected area using sessions. That is a known bug. I posted a fix that's been working for me in the comments of http://www.asfusion.com/blog/entry/file-upload-with-coldfusion-flash-forms
Federico,
The updater made a "fix" to cffile upload. To have it working as it was, you need to install the latest hotfix or upload the file and rename it manually after.
Laura
No, it is not possible to embed a pdf in Flash and therefore Flex. You need to open it a new window/frame or make it Flash Paper instead.
Robert
<CFFILE ACTION="RENAME" DESTINATION="..\video\raw_videos\#newfilename#.avi" SOURCE="../video/raw_videos/#filedata#">
What changes do I need to make? Thanks.
KenM
Now I need another tab page with input areas for 3 different file names/paths. So how do I have 1 submit button that sends all of that up? Do I need a separate "Upload" button for each of the file inputs and after clicking those, the use then clicks the form submit? Apparently George got it - I'm still struggling.
Thx much
Laura
to get the original file name, use form.filename. filedata is the actual data field, not the name.
KenM,
You cannot post anything other than the file. You can only send variables via query string. Otherwise, submit the form for the other fields.
For many upload fields, you can use this custom tag:
http://www.asfusion.com/blog/entry/file-upload-with-coldfusion-flash-forms
check the example where the submit is triggered from another button (last example). You will trigger all the file uploads at once.
Gene Rice
Can I return just the name, (myfile). I want to be able to append something after that, before the extension. i.e. myfile_resized.jpg
Thanks in advance.
Laura
selectedFile.name includes everything. You will need to do some string parsing if you want to separate the extension.
Gomez
Jenny
Thanks again for a fantastic example! You guys are awesome!
Justin - thanks for asking that question. I was having the same issue and resolved it by reading their reply to you.
Tadas
i have a question:
i use flash to upload images to database and i'm calling .net webservice to save file to database. After the images is saved, webservice returns back ID (or GUID) of the image, how can i return it back to flash swf?
like : oncomplete, get some values from http response...
Thanks a lot.
Tadas
Clara
Thanks for this awesome info. I was wondering if it's possible to upload large music files as well. Ultimately, I'd like to find a way to upload music files, convert them to a chosen format, then put them up on a website.
Do you know if online conversion of music has been done yet, or if it's something that will happen soon?
Apologies that I'm not a programmer, so these may be silly questions :o)
Chego Huang
I hack your upload-image-renamed.cfm & upload-image-action.cfm
We can use *.jpg;*.png;*.gif, and every onece Upload Image have a random filename.
upload-image-renamed.cfm
<cfsavecontent variable="uploadScript">
var uploadSwf = textArea.label.upload;
var id:Number = Math.floor(Math.random() * 100000001);
myform.id = id;
uploadSwf.upload("upload-image-action.cfm?id=" + myform.id);
//....//
</cfsavecontent>
<cfsavecontent variable="browseScript">
//....//
uploadSwf.browse([{description: "Image Files (*.jpg;*.png;*.gif)", extension: "*.jpg;*.png;*.gif"}]);
//....//
uploadListener.onComplete = function(file:FileReference)
{
output.text = "Upload complete";
//myform.picture = myform.id + ".jpg";
myform.picture = myform.id + file.type;
uploadBtn.enabled = false;
browseBtn.enabled = true;
}
<cfform name="myform" height="500" width="730" format="Flash" timeout="0" skin="haloBlue">
//....//
<cfinput type="hidden" name="id" value="" />
</cfform>
upload-image-action.cfm
<cfif structkeyexists(form,"Filedata")>
<!--- upload file with whatever attributes you need, additional variables may come in url scope --->
<cfset ext = Right(form.filename,4)>
<cffile action="UPLOAD" filefield="Filedata" destination="#expandpath(".")#\#url.id##ext#" nameconflict="OVERWRITE">
</cfif>
Matt Haughey
Any idea what's up?
Laura
Are you able to browse the upload.cfm file?
For status codes, check:
http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
Matt Haughey
Here's the demo on my server:
http://www.metafilter.com/test/upload-image/
I have the live headers extension for firefox and I checked the apache error logs, but I'm not seeing where a 301 redirect is coming from. I assume it might be some of the /CFIDE libraries or something.
Laura
Unfortunately, live http headers do not show the call to the file upload script, not sure why. I've been able to see the call by using Fiddler only.
Matt Haughey
http://www.metafilter.com/test/upload-image/upload.cfm
Eric Joseph
2: is there a way of making the image small enough so it's displayed in its entirety?
thnx
Mark Johnson
I am trying to make changes so that the image is uploaded into the /images directory instead of the root. When I change the destination - destination="#expandpath(".")#/images" like this, it will put it into the images directory but it then uses the original filename and not the old filename. Any help would be greatly appreciated.
Laura
1. Do you mean limiting the allowable file size?
2. You can set the width and height in the img tag.
Mark,
I would store the file and then rename it afterwards. There are issues when trying to rename and save at the same time.
Simon
Is it possible to upload an image say random.gif and then change the name and file extension say to userid.swf.
Why?
1.well the image name would be unique and identified to a user.
2.It is possible to show a gif in flashplayer by just changing the extension. If this could be done on upload then this swf can be a gif in disguise and thus can be {binded} to things like image buttons.
Any code hints would be appreciated thanks.
Laura
If you look at the source you will see we change the name of the file on the server. You can always change the file extension as well, which it does not mean the player will be able to load it or use it just because the file extension matches an allowed type.
Simon
Thankyou kindly for your response. Your site has become a knowledge base for me.
I have found the section of code that changes the extension. You are right, even though changing a .gif to a swf file extension causes the gif to open in a flash player the flash player still recognises it as a gif and thus does not display it on the fly.
Eric
thanks for the response.
1: yes the allowable size. to allow for bigger files, say up to 3MB
2: would changing the height + width show the whole image though?
i'd like it to show the whole image, online in a box of say, 300 x 300 pixels.
i found out that anything else i try shows the image from the top left corner. so if the image in too big, u may not see the subject @ the center
Simon
You need to scale the image.
Check out http://www.opensourcecf.com/imagecfc/ , this seems to the trick.
You can reference this cfc on the action page to scale the image.
Hope this helps
Simon
To adjust the allowable file size look for the line
var maxSize = 1024 * 200;
200 represent 200kb so to make 3mb change to:
var maxSize = 1024 * 3000;
Mathew
Just wondering if there had been any update from Tadas' earlier post:
Is it possible to return an ID or GUID via the onComplete event in the flash?
Thanks
Eric
thank you for the response.
the file size limit worked perfectly
i'm having issues on the scaling though
i'm pretty novice and am not sure where/how
to reference the image.cfc i downloaded from
the URL u posted. could you help me there?
thnks again
Simon
Dont want to use Asfusion as a forum to advertise someone else but quickly just to help out.
(if jpg use the following, if not jpg consider a similar approach as comment 44 to save other file types [although there are some issues with the code used on 44 particularly .'myform.picture = myform.id + file.type;'. Please keep in mind as far as i know flash player will only display jpg and swf dynamically [ie after runtime])
Anyway more to the point (scaling an image to fit in a 150 width by 50 height space)
Use the cfc on the action page.
<!---ASfusion code--->
<cffile action="UPLOAD" filefield="Filedata" destination="#expandpath("rawimages/.")#\#url.id#" nameconflict="OVERWRITE">
<!---USE CFC--->
<cfset imagecfc = createObject("component","image")>
<!---Scale raw image and save in new location--->
<cfset resultsx = imageCFC.scaleX("", "#ExpandPath("rawimages/.")#/#url.id#", "", 150)>
<cfset resultsy = imageCFC.scaleY(resultsx.img, "","#ExpandPath("properimages/.")#/#url.id#", 50)>
I hope this helps. If it doesnt check out the examples on their website otherwise leave another post. I will check back.
Cheers
Simon
Simon
Thanks
Simon
Does anyone know how to flush the image cache.
I dont want to save as a random number. So say i save as 1.jpg and then load another image and save as 1.jpg the old one still displays. I want the new one to always display. Thanks.
Laura
No, nothing can be returned from the upload action page and that is why we used a random name that we know in advance (see that in the source).
Helen
How can i add a grid next to the upload panel
that shows the files on the
destination folder ! (filename and size)
AND have the grid update it's content
with every new upload ?????
PLEASE anyone got a clue ???
thanxs
Laura
Have you taken a look that the File Explorer? http://www.asfusion.com/projects/fileexplorer/ It does what you want, although it uses Flash Remoting for that. You could also add the item to the grid contents if you don't want to use remoting.
VIjay
Am working in Asp.net application, When am updating the page its properly works in Internet Explorer but not works in other browsers(Opera, Mozila).Here updates performed in the database but the page displays blank.I dono wats the reason,Please help anyone....
Advance thanks,
Thanks&Regards
Vijay
Joe
Nate
Kevin
Is there a way that I can submit the form from the onComplete function? I tried it several ways and none of them were successful Truthfully, I couldn't even get the following code to work in the onComplete function:
uploadListener.onComplete = function()
{
output.text = "Upload complete";
getURL("Javascript:alert('hi')");
uploadBtn.enabled = false;
browseBtn.enabled = true;
}
why doesn't the getURL trigger? What am I doing wrong? How can I access Javascript from within the onComplete function? Is there a "submit()" function in actionscript like there is in javascript?
Thanks a million and a half (inflation) for anybody who can give me a hand with this!
Kevin
Oh, wait....that was me. DOH! ;)
Sorry for neglecting the #1 rule of forum posting......and thanks to everybody who has put so much effort into helping each other out.
Juan Pablo
Also, I could pay a few money for this job. THANKS TO ALL!!!
Ben
I see that you talked about this already in the past but i'm trying to do the _root.submitForm() that you mentioned earlier to have another page process the form fields but it's not working for me.
I put the _root.submitForm() in the uploadListener.onComplete function and gave the cfform an action variable but alas it's not working. Would anyone have some insight as to what i should do about this?
Thank you very much in advance.
Ben
netcru
the following didn't work:
if ((condition=1) and (condition=2)) { somthing...}
if ((condition=1) & (condition=2)) { somthing...}
if ((condition=1) &&(condition=2)) { somthing...}
Laura
You mean inside the ActionScript code?
if (condition == 1) && (condition == 2) { }
netcru
Is there a way to put a progress bar for CFFTP?
John
if(selectedFile.size < maxSize || maxSize == undefined)
{
uploadBtn.enabled = true;
output.text = "";
}
else
{
output.text = "The file selected exceeds maximum allowed size";
uploadBtn.enabled = false;
}
Any ideas if this is possible and where I should start?
jhov
Thanks in advance for your help!
Don from DC
Thanks for any help.
bharathi
i am having problem while uploading photo
i can upload photo,the problem is after uploading photo,it has to display the uploaded photo in another jsp.
Kurt
Kate Juliff
Kate Juliff
Rene
First, your Website is genius!! I never saw anything like this before!!! Just great!
But i have a big Problem which is discussed in this forum before, but i can't solve it anyway. I tried nearly everything.
I talk about a Flash based upload form. Everything works fine when i install my scripts outside of a memberbased Area. But if i place it insinde, the "choose File" Button won't bring me up an window from which i can choose my file to be uploaded. i tried it with the hidden cfinput, but nuthin changes.
I would be so glad if you guys can give me a good advise on how to handle the problem....
Greetz René
Johan
How to view my browsed image without upload it? How to get the full path?
Thank's in advance
Neo
I just would like add a <cfmail> tag to send email when upload will be finishing, how to do ?
I try to put cfmail tag on uploadListener.onComplete function, but ofcourse that dont work because we rae in actionscript and not in cfm page.
Somebody have an idea ?
Many thanks
Neo
FuzzySiberians
Jason
Any help on instructions on where to start with these files would be appreciated.
Thanks in advance
Jason
How does the following code link into the CFN files? I'm having trouble getting them to all work together.
______________
import flash.net.FileReference;
var imageFile:FileReference = new FileReference();
function addListener(listener:Object):Void
{
imageFile.addListener(listener);
}
function browse(list:Array):Void
{
imageFile.browse(list);
}
function upload( path:String):Boolean
{
return imageFile.upload(path);
}
function cancel():Void
{
imageFile.cancel();
}
Jason
Any help would be appreciated.
Thanks
brant