Solved

CFFILE upload help

Posted on 2016-08-31
98
112 Views
Last Modified: 2016-09-26
I am trying to upload file to the server using jquery ajax, but getting an error message Invalid content type: application/x-www-form-urlencoded. My form has enctype="multipart/form-data".

the jquery looks like this

 $('#taskForm').submit(function (e) {
		e.preventDefault();
		var uplFile = $('#fileAttached').val();
		var forms=($(this).serialize());
      $.ajax({
        type: 'POST',
      
        url: '/includes/task.cfc?method=addEditTask',
        data: forms + '&fileAttached=' + encodeURIComponent(uplFile),
        cache:false,

        success: function () {
         alert('Uploaded')
      });
		return false;

    });

Open in new window

0
Comment
Question by:erikTsomik
  • 46
  • 45
  • 5
  • +1
98 Comments
 
LVL 19

Author Comment

by:erikTsomik
ID: 41779255
any suggestions
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41779374
EDIT FormData used in the sample below only works with IE10 and above
How to upload with AJAX
HTML
    <form>
      Your Name: <input type="text" name="name" /> <br/>
      File #1 <input type="file" name="file1" /> <br/>
      File #2 <input type="file" name="file2" /> <br/>
      <input type="submit" />
    </form>
    <div id="result"></div>

Open in new window

JQuery
$(function() {
  $('form').submit(function() {
    var formData = new FormData($(this)[0]);
    $.ajax({
      url: 'reflect.php',
      type: 'POST',
      data: formData,
      cache: false,
      contentType: false,
      processData: false
    }).then(function(data) {
      $('#result').html(data);
    });    
    return false;
  });
});

Open in new window

Working sample here
Sample posts data to a script that just reflects the data back.
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41779377
With reference to the above have a look at FormData
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41779798
I need to make sure it will work  in Chrome, Safari and mobile devices
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41779810
Support for AJAX uploads is fairly new (refer supported platforms in the FormData Link I posted earlier)- if you want to support legacy devices you will need to look at the <iframe> method and / or have a look at plugins like the BlueImp downloader

https://github.com/blueimp/jQuery-File-Upload
1
 
LVL 24

Expert Comment

by:dgrafx
ID: 41780064
Have you tried plupload? It works with all the browsers you mentioned.

http://www.plupload.com/

Very very nice uploader with options such as drag and drop ...
1
 
LVL 19

Author Comment

by:erikTsomik
ID: 41780093
Julian Hansen. Just tried your example but the ajax  is keep on running and its does not finish
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41780345
Just tried your example but the ajax  is keep on running and its does not finish
How big were the files you tried to upload? Make sure they are small as there are limits on that server in terms of uploads. It may also be an issue with my soon to be ex-hosting provider.

Have you tried the code on your server?
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41780346
The files are small 300k
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41780368
Erik
Have you tried plupload?
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41780410
I did not try that
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41780514
If you try it all your problems will disappear!
And it's free ...
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41780598
dgrafx I need plupload to work on the submit button click just like posted. Beacause there are some DB action upon submition
0
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 41780695
Just did a 600K and 800K upload - works.

Please bear in mind that this server is on the end of a slow link comparatively speaking - it does not run at the speeds you are probably used to - which is why I suggested you try it on your local server.
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41780740
That would be just a matter of a few lines of code - no big deal ...
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41780746
Can you show me an example how that can be accomplished
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41780761
Later as I'm not in front of computer right now.

Or you can set plupload to upload automatically when file is added.
You just need tag the uploads with a unique session id
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41780894
OK this code is directly from the online examples

<div id="uploader">
    <p>Your browser doesn't have Flash, Silverlight or HTML5 support.</p>
</div>
 
<script type="text/javascript">
// Initialize the widget when the DOM is ready
$(function() {
    $("#uploader").plupload({
        // General settings
        runtimes : 'html5,flash,silverlight,html4',
        url : "/examples/upload",
 
        // Maximum file size
        max_file_size : '2mb',
 
        chunk_size: '1mb',
 
        // Resize images on clientside if we can
        resize : {
            width : 200,
            height : 200,
            quality : 90,
            crop: true // crop to exact dimensions
        },
 
        // Specify what files to browse for
        filters : [
            {title : "Image files", extensions : "jpg,gif,png"},
            {title : "Zip files", extensions : "zip,avi"}
        ],
 
        // Rename files by clicking on their titles
        rename: true,
         
        // Sort files
        sortable: true,
 
        // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
        dragdrop: true,
 
        // Views to activate
        views: {
            list: true,
            thumbs: true, // Show thumbs
            active: 'thumbs'
        },
 
        // Flash settings
        flash_swf_url : '/plupload/js/Moxie.swf',
     
        // Silverlight settings
        silverlight_xap_url : '/plupload/js/Moxie.xap',
		
		init : {
        FilesAdded: function(up, files) {
          up.start();
        }
		}
    });
});
</script>

Open in new window


The idea here is that when a user adds a file it is uploaded right away - so you may want to hide the Start Upload button.

Good luck ...
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41780901
Is there way the upload can happen on the submit button click
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41780924
I'll need to get in front of a computer for that.
In the meantime look at this link - it might be what I'm wanting but will need to test it
http://stackoverflow.com/questions/22777604/files-upload-at-form-submit-button-with-plupload
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41780930
Fyi: to remove auto upload comment out
init : {
        FilesAdded: function(up, files) {
          up.start();
        }
		}

Open in new window

And it's preceding comma
0
 
LVL 15

Expert Comment

by:myselfrandhawa
ID: 41781802
ok, so flash is out of date use the following article to upload the fiile by jquery and ajax

https://www.experts-exchange.com/articles/10549/Upload-the-File-Using-jquery-coldfusion-and-Preview-It.html
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41781865
Note that to a person that can read code one can see that flash is used as a backup only for old browsers that don't support HTML5
Just FYI ...

erik - I will post some more later - am really busy right now ...
did you have any luck with that article?
1
 
LVL 24

Expert Comment

by:dgrafx
ID: 41782077
OK Erik
Just add this right before your closing </script> tag in the example code I posted yesterday:
function uploadit() {
	$('#uploader').plupload('start');	
}

Open in new window

and don't forget to comment out what I said yesterday as well

Then here is a button that will trigger the upload and submit your form
<input type="button" onclick="uploadit(); submit();" value="Submit">

Open in new window


good luck ...
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41782084
Thank you I will try it and let you know how it goes
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41782087
Start with a working example - the code I posted is right from their online demos.
Then modify as you see fit.
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41786655
I tried the code but it does not working for me it seems like it does not recognizing the library. Do i need jquery library to ran this code. I have 1.6.1 installed
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41786680
Go to the online demos and grab whatever files are required
There is jQuery probably and there's plupload js as well
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41786685
the jquery will interfere with my existing library
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41786787
What is your existing Library?
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41786801
1.6.1
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41786805
Just comment out your 161 and use the more modern one
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41786846
I can not comment one out because most of my app is built of 1.6.1
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41786989
I doubt that it matters - it's just a version of JQuery!
Are you referring to actual errors or are you just worried there might be? You'll need to try it out if you haven't  ...
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41789605
Erik - how's it going? Any roadblocks?
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41789659
I can not change the jquery there are many unexpected behaviors once i do that . So I guess I am stock here  with upload
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41789680
so you did try and change the jquery version?
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41789693
yes I did
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41789697
and you were then throwing errors in the rest of your app?
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41789702
NOt all by a lot of places. I have over 300 pages
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41789712
what do you mean?
a couple errors here and there?
or do you mean no errors but haven't tested all 300 pages?
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41789716
tested a lot of pages and was throwing error messages on a lot of them
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41789724
ok so was it the same error and is the same code (that is erroring) on all of these pages?
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41789730
Yes was the same code
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41789731
The same error message
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41789745
ok so let's fix it - you can probably do an extended find then extended replace
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41789759
what is the most stable version of jquery and UI library
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41789784
Well jquery version 3 is out and stable

Another idea is to see if plupload will run on your 161 version.
If it does then this is the fastest fix of course.
I kinda got the idea that it wasn't working before but am not sure that's what you said or meant.
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41789991
I finally found jquery library that works for my site. And when I am trying to run plupload. I get an error message saying plupload is not a function
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 24

Expert Comment

by:dgrafx
ID: 41790006
you need the appropriate files as well

The CSS
<link type="text/css" rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/smoothness/jquery-ui.min.css" media="screen" />
<link type="text/css" rel="stylesheet" href="http://www.plupload.com/plupload/js/jquery.ui.plupload/css/jquery.ui.plupload.css" media="screen" />

The JS - this first jquery js file is replaced with your jquery js file
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js" charset="UTF-8"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="http://www.plupload.com/plupload/js/plupload.full.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="http://www.plupload.com/plupload/js/jquery.ui.plupload/jquery.ui.plupload.min.js" charset="UTF-8"></script>
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41790083
OK. First I got it the plupload to show up . Then When I click on upload
I getting error message Invalid content type: application/x-www-form-urlencoded; charset=UTF-8. in ColdFusion when trying to upload
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41790145
And that is on your action page correct?
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41790188
that happens when the button is clicked the form itself has enctype param. And then I am sending control over to ColdFusion function wich is the action.
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41790226
Right - but that's a CF error on action page.
Post your action function or page.
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41790238
 <cftransaction isolation="serializable">
       	    	<cfquery datasource="#Request.datasource#">
       	    		UPDATE task
       	    		  SET name =  <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.name#">,
       	    		      description = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.description#">,
       	    		      status = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.status#">,
       	    		      priority = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.priority#">,
       	    		      categoryID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.category#">
       	    		      <cfif StructKeyExists(arguments,"isSingleParticipant")>
       	    		          ,isSingleParticipant = <cfqueryparam cfsqltype="cf_sql_bit" value="1">
       	    		      <cfelse>
       	    		         ,isSingleParticipant = <cfqueryparam cfsqltype="cf_sql_bit" value="0">
       	    		      </cfif>
       	    		      <cfif StructKeyExists(arguments,"category") and ListFindNoCase("3,4,5,6,7,8",arguments.category)>
                           ,carKey = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.carKey#">
                       <cfelse>
                            ,carKey = NULL
                       </cfif>
                        <cfif StructKeyExists(arguments,"category") and ListFindNoCase("3,4,5,6,7,8",arguments.category)>
                           ,costPerTask = <cfqueryparam cfsqltype="cf_sql_float" value="#arguments.costPerTask#">
                       <cfelse>
                            ,costPerTask = NULL
                       </cfif>
                        ,taskStart = <cfqueryparam value="#arguments.fromDate#" cfsqltype="cf_sql_timestamp" null="#IIf(Len(Trim(arguments.fromDate)), DE("no"), DE("yes"))#">
                        ,taskEnd = <cfqueryparam value="#arguments.toDate#" cfsqltype="cf_sql_timestamp" null="#IIf(Len(Trim(arguments.toDate)), DE("no"), DE("yes"))#">

       	    		WHERE taskID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.taskID#">
       	    	</cfquery>

       	    	

                <cfif IsDefined("arguments.fileAttached") AND Len(Trim(arguments.fileAttached))>
                	#request.Filedestination#
                    <cffile
                        action = "upload"
                        fileField = "arguments.fileAttached"
                        destination = "#request.Filedestination#"
                        nameConflict = "overwrite" />

                     <cfset extList = "jpg,gif,tif,pdf,jpeg,pdf" />
                    <cfset thisExt = ListLast(FILE.ServerFile, ".") />

                     <cfif ListFindNoCase(extList, thisExt) NEQ 0>
                        <cfset newName = "#arguments.taskID#.#FILE.ServerFileExt#" />

                         <cffile action="copy"
                            source="#request.Filedestination#\#FILE.ServerFile#"
                            destination="#request.Filedestination#\#newName#"
                            nameconflict="overwrite" />

                        <cfquery datasource="#Request.datasource#">
                            UPDATE task
                            SET fileAttached = <cfqueryparam cfsqltype="cf_sql_varchar" value="#newName#">
                            WHERE taskID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.taskID#">
                        </cfquery>
                     </cfif>
                </cfif>

       	    </cftransaction>

Open in new window

0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41790245
I will get back to you later - I'm offline right now ...
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41790278
OK
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41790484
Use this for your upload function:

<cfscript>
   source = Application.rootPath & "/assets/uploadchunks/";
   destination=Application.rootPath & "/assets/uploads/";
   fileExtension = listLast( form.name, "." );
   filename = createUUID() & "." & variables.fileExtension;
   //filename = 'tester.txt'; // this is for testing so that files keep getting overwritten 
   
    if ( isNull( form.chunks ) ) {
        fileMove(
            form.file,
			expandPath(variables.destination & variables.filename)
        );
    } else {       
        upload = fileOpen( expandPath( variables.source & form.name ), "append" );
        fileWrite( upload, fileReadBinary( form.file ) );
        fileClose( upload );
        if ( form.chunk == ( form.chunks - 1 ) ) {
            fileMove(
                expandPath(variables.source & form.name),
				expandPath(variables.destination & variables.filename)
            );
        }
    }
</cfscript>

<!--- Reset the content buffer. --->
<cfcontent
    type="text/plain"
    variable="#charsetDecode( 'success', 'utf-8' )#"
    />

Open in new window

0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41791649
Just to be clear on what I doing . Here is my form . My backend doesnot know what the form dname is OR I am overlooking something


<form class="form-horizontal" role="form" id="taskForm"  method="POST" enctype="multipart/form-data">
 <div class="form-group" id="costPerTaskSection">
      <label class="control-label col-sm-2" for="email">Compensation ($):</label>
      <div class="col-xs-10">
        <input type="text" class="form-control" id="costPerTask" name="costPerTask" placeholder="Amount"  value="<cfoutput>#qGetTask.costPerTask#</cfoutput>">
        <span class="help-block">Enter the amount that the task tarticipant will receive upon completion of the task.</span>
         <div class="help-block with-errors"></div>
      </div>
    </div>

<div class="form-group" id="uploader">
    	<label class="col-xs-2">Attach a File:</label>
         <div class="col-xs-10"><input type="file" name="fileAttached" id="fileAttached" /></div>
        <span class="help-block"></span>
         <div class="help-block with-errors"></div>
    </div>

  <div class="form-group">
      <div class="col-sm-offset-2 col-sm-10">
        <button type="submit" class="btn btn-success" id="btnSubmit">Submit</button>
       
      </div>
    </div>
  </form>
</form>

Open in new window


Here is JS
 function uploadit() {
        $('#uploader').plupload('start');
       }


$("#uploader").plupload({
        // General settings
        runtimes: 'html5,flash,silverlight,html4',

        // Fake server response here
        // url : '../upload.php',
        //url: "/echo/json",

        // Maximum file size
        max_file_size: '1000mb',

        // User can upload no more then 20 files in one go (sets multiple_queues to false)
        max_file_count: 20,

        chunk_size: '1mb',

        // Resize images on clientside if we can
        resize : {
            width: 200,
            height: 200,
            quality: 90,
            crop: true // crop to exact dimensions
        },

        // Specify what files to browse for
        filters: [
            { title: "Image files", extensions: "jpg,gif,png" },
            { title: "Zip files", extensions:  "zip,avi" }
        ],

        // Rename files by clicking on their titles
        rename: true,

        // Sort files
        sortable: true,

        // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
        dragdrop: true,

        // Views to activate
        views: {
            list: true,
            thumbs: true, // Show thumbs
            active: 'thumbs'
        },

        // Flash settings
        flash_swf_url : 'http://rawgithub.com/moxiecode/moxie/master/bin/flash/Moxie.cdn.swf',

        // Silverlight settings
        silverlight_xap_url : 'http://rawgithub.com/moxiecode/moxie/master/bin/silverlight/Moxie.cdn.xap'
    });


$('#taskForm').submit(function (e) {
        uploadit();
		e.preventDefault();
		var uplFile = $('#fileAttached').val();
        var forms=($(this).serialize());

           if ($('#uploader').plupload('getFiles').length > 0) {

            // When all files are uploaded submit form
            $('#uploader').on('complete', function() {
                $('#taskForm')[0].submit();
            });

            $('#uploader').plupload('start');
        } else {
            alert("You must have at least one file in the queue.");
        }



      $.ajax({
        type: 'POST',
        url: '/includes/task.cfc?method=addEditTask',
        data: forms + '&fileAttached=' + encodeURIComponent(uplFile),
        cache:false,
        contentType:"application/json; charset=utf-8",
        success: function () {
          $.get('/includes/task.cfc?method=getTasks&taskOwner=<cfoutput>#session.userKey#</cfoutput>',
            function (result) {
            	 $("#taskListing").html(result);
            	 $("#dialog").dialog( "destroy" );
            	 $("#dialog").dialog('close');
                 $("#dialog").html('');
            }
          )
        }
      });
		return false;
    });

Open in new window


Here is my backend ColdFusion function page

 <cftransaction isolation="serializable">
       	    	<cfquery datasource="#Request.datasource#">
       	    		UPDATE task
       	    		  SET name =  <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.name#">,
       	    		      description = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.description#">,
       	    		      status = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.status#">,
       	    		      priority = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.priority#">,
       	    		      categoryID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.category#">
       	    		      <cfif StructKeyExists(arguments,"isSingleParticipant")>
       	    		          ,isSingleParticipant = <cfqueryparam cfsqltype="cf_sql_bit" value="1">
       	    		      <cfelse>
       	    		         ,isSingleParticipant = <cfqueryparam cfsqltype="cf_sql_bit" value="0">
       	    		      </cfif>
       	    		      <cfif StructKeyExists(arguments,"category") and ListFindNoCase("3,4,5,6,7,8",arguments.category)>
                           ,carKey = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.carKey#">
                       <cfelse>
                            ,carKey = NULL
                       </cfif>
                        <cfif StructKeyExists(arguments,"category") and ListFindNoCase("3,4,5,6,7,8",arguments.category)>
                           ,costPerTask = <cfqueryparam cfsqltype="cf_sql_float" value="#arguments.costPerTask#">
                       <cfelse>
                            ,costPerTask = NULL
                       </cfif>
                        ,taskStart = <cfqueryparam value="#arguments.fromDate#" cfsqltype="cf_sql_timestamp" null="#IIf(Len(Trim(arguments.fromDate)), DE("no"), DE("yes"))#">
                        ,taskEnd = <cfqueryparam value="#arguments.toDate#" cfsqltype="cf_sql_timestamp" null="#IIf(Len(Trim(arguments.toDate)), DE("no"), DE("yes"))#">

       	    		WHERE taskID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.taskID#">
       	    	</cfquery>

       	    	<cfif StructKeyExists(arguments,"part") and listLen(arguments.part)>
       	    		<cfquery datasource="#request.datasource#">
       	    			DELETE
       	    			FROM task_participants
       	    			WHERE taskID = <cfqueryparam cfsqltype="cf_sql_integer"value="#taskID#">
       	    		</cfquery>

               

                <cfif IsDefined("arguments.fileAttached") AND Len(Trim(arguments.fileAttached))>
                	#request.Filedestination#
                    <cffile
                        action = "upload"
                        fileField = "arguments.fileAttached"
                        destination = "#request.Filedestination#"
                        nameConflict = "overwrite" />

                     <cfset extList = "jpg,gif,tif,pdf,jpeg,pdf,txt" />
                    <cfset thisExt = ListLast(FILE.ServerFile, ".") />

                     <cfif ListFindNoCase(extList, thisExt) NEQ 0>
                        <cfset newName = "#arguments.taskID#.#FILE.ServerFileExt#" />

                         <cffile action="copy"
                            source="#request.Filedestination#\#FILE.ServerFile#"
                            destination="#request.Filedestination#\#newName#"
                            nameconflict="overwrite" />

                        <cfquery datasource="#Request.datasource#">
                            UPDATE task
                            SET fileAttached = <cfqueryparam cfsqltype="cf_sql_varchar" value="#newName#">
                            WHERE taskID = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.taskID#">
                        </cfquery>
                     </cfif>
                </cfif>

       	    </cftransaction>

Open in new window

0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41791665
in your div id="uploader" you need to remove the input type = file
don't try to combine plupload with input type = file or cffile - this is a different technology
and in your plupload function you need to provide the url of the plupload action code I posted

all this is detailed in the online examples
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41791668
But I want to upload to happened once the button is clicked and also update the database. Do i need to have 2 separate functions to do the file upload and database update?
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41791681
well you need to have code similar to the code I posted to accept the upload via plupload (the cfscript I posted).
then your form submits with other form fields whatever they may be
you need to store uploaded file names in a persistent variable like session to tie the form together with the upload

do you understand?
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41791686
I did not get the fact when The  upload file is selected how to pass it to the function (like old fashion way used to do) in your cfcsript you tell to use form.chunk
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41791690
I can post a simple working model later
you always ask these questions when I'm on my way out ...
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41791694
OK.That will be awesome
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41792193
ok so there are 2 files - formpage.cfm & actionpage.cfm
they are functional so set them up as is modifying as needed
the concept is that on your action function you do something with the uploaded files I'm guessing so now to access the uploaded files you have the session var "formid" to locate them. just move them to wherever.
Then delete the formid folder or delete all user files on a schedule or ???
And instead of formid you could use a session id if users that will be uploading are logging in ...

<CFPROCESSINGDIRECTIVE SUPPRESSWHITESPACE="Yes">
****************************************************
Form Page
****************************************************

<link type="text/css" rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/smoothness/jquery-ui.min.css" media="screen" />
<link type="text/css" rel="stylesheet" href="http://www.plupload.com/plupload/js/jquery.ui.plupload/css/jquery.ui.plupload.css" media="screen" />

<cfif Not StructKeyExists(session,"formid")>
	<cflock scope="session" timeout="15" type="exclusive">
		<cfset session.formid=CreateUUID()>
	</cflock>
</cfif>

<cfoutput>
<form id="taskform">
	<input type="hidden" name="formid" value="#session.formid#">
	<input type="text" style="width:200px" name="name" placeholder="What is your Name?" value="dgrafx" /><br />
	<input type="text" style="width:200px" name="quest" placeholder="What is your Quest?" value="I seek the grail" /><br />
	<input type="text" style="width:200px" name="color" placeholder="What is your Favorite Color?" value="blue" /><br />
	
	<div id="uploader" style="width:500px">
	    <p>Your browser doesn't have Flash, Silverlight or HTML5 support.</p>
	</div>

	<input type="button" class="submiter" value="Submit">
</form>
</cfoutput>	

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js" charset="UTF-8"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="http://www.plupload.com/plupload/js/plupload.full.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="http://www.plupload.com/plupload/js/jquery.ui.plupload/jquery.ui.plupload.min.js" charset="UTF-8"></script>

<script>
<cfoutput>var formid = '#session.formid#';</cfoutput>
$(function() {
    $("#uploader").plupload({
        runtimes : 'html5,flash,silverlight,html4',
        url : "actionpage.cfm?formid="+formid,
        max_file_size : '6mb',
        chunk_size: '1mb',
        resize : {
            width : 200,
            height : 200,
            quality : 100,
            crop: true 
        },
        filters : [
           {title : "File Types", extensions : "png,jpg,gif"}
        ],
        rename: true,
        sortable: true,
        dragdrop: true,
        views: {
            list: true,
            thumbs: true, 
            active: 'thumbs'
        },
        flash_swf_url : 'assets/js/Moxie.swf',//set this path to where this files is
        silverlight_xap_url : 'assets/js/Moxie.xap'//set this path to where this files is
    });	
	
	$(document).on("click", ".submiter", function() {
	//$('form').submit(function(e) {	
	    var uploader = $('#uploader').plupload('getUploader');
		var data = $('#taskform').serialize();
	    // Validate number of uploaded files
	    if (uploader.total.uploaded == 0)
	    {
	        // Files in queue upload them first
	        if (uploader.files.length > 0)
	        {
	            // When all files are uploaded submit form
	            uploader.bind('UploadProgress', function ()
	            {
	                 $('#uploader').on('complete', function() {
					 
					   $.ajax({
							type: 'post',
							data: data,	
							url: 'actionpage.cfm',
							success: function(result) {
								console.log('success');						
							}
						});
	
	                 });
	            });
	
	           $('#uploader').plupload('start');
	        } 
			else { 
								
				$.ajax({
					type: 'post',
					data: data,	
					url: 'actionpage.cfm',
					success: function(result) {
						console.log('success');						
					}
				});
			
			}
			
	    }	
	});
	
});
</script>
</CFPROCESSINGDIRECTIVE>

Open in new window


****************************************************
Action Page
****************************************************

<cfif StructKeyExists(url,"formid")>
	<cfscript>
		if(! directoryExists(expandPath("/uploads/") & url.formid)) {
			directoryCreate(expandPath("/uploads/") & url.formid);
		}
		if(! directoryExists(expandPath("/uploadchunks/") & url.formid)) {
			directoryCreate(expandPath("/uploadchunks/") & url.formid);
		}
	   source = "/uploadchunks/" & url.formid & "/";
	   destination = "/uploads/" & url.formid & "/";
	   filename = form.name;
	   
	    if ( isNull( form.chunks ) ) {
	        fileMove(
	            form.file,
				expandPath(variables.destination & variables.filename)
	        );
	    } else {       
	        upload = fileOpen( expandPath( variables.source & form.name ), "append" );
	        fileWrite( upload, fileReadBinary( form.file ) );
	        fileClose( upload );
	        if ( form.chunk == ( form.chunks - 1 ) ) {
	            fileMove(
	                expandPath(variables.source & form.name),
					expandPath(variables.destination & variables.filename)
	            );
	        }
	    }
	</cfscript>
<cfelse>
	
	<!--- this is where form is submitted to - put all your stuff in this leg of this cfif block --->
	
</cfif>

<!--- Reset the content buffer. --->
<cfcontent
    type="text/plain"
    variable="#charsetDecode( 'success', 'utf-8' )#"
    />

Open in new window

0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41792244
I got the code to work, So the only question that I have how can I get the name of the file back so I can put it into the database
0
 
LVL 15

Expert Comment

by:myselfrandhawa
ID: 41792261
out of question, did u tried the code in tute link i gave, i know this makes no sense as u are too ahead with pupload.
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41792847
I will be back online later today - stay tuned ...
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41793053
Thanks dgrafx
0
 
LVL 24

Accepted Solution

by:
dgrafx earned 500 total points
ID: 41793073
Erik
Here is a slightly different method - it's what I had suggested first.
There were too many issues the other way that came to light after more in depth testing.
Note that the issues may have been surmountable but it would take "time"
So set this up and see how slick it works

<CFPROCESSINGDIRECTIVE SUPPRESSWHITESPACE="Yes">
****************************************************
Form Page - formpage.cfm
****************************************************

<link type="text/css" rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/smoothness/jquery-ui.min.css" media="screen" />
<link type="text/css" rel="stylesheet" href="http://www.plupload.com/plupload/js/jquery.ui.plupload/css/jquery.ui.plupload.css" media="screen" />
<cfif Not StructKeyExists(session,"formid")>
	<cflock scope="session" timeout="15" type="exclusive">
		<cfset session.formid=CreateUUID()>
	</cflock>
</cfif>

<h3>First step is to add your files!!!</h3>

<div id="uploader" style="width:500px">
	<p>Your browser doesn't have Flash, Silverlight or HTML5 support.</p>
</div>

<h3>Then fill out this form!!!</h3>

<cfoutput>
<form id="taskform">
	<input type="hidden" name="formid" value="#session.formid#">
	<input type="text" style="width:200px" name="filelist" id="filelist" placeholder="filelist"><br />
	<input type="text" style="width:200px" name="name" placeholder="What is your Name?" value="dgrafx" /><br />
	<input type="text" style="width:200px" name="quest" placeholder="What is your Quest?" value="I seek the grail" /><br />
	<input type="text" style="width:200px" name="color" placeholder="What is your Favorite Color?" value="blue" /><br />
	<input type="button" class="submiter" value="Submit">
</form>
</cfoutput>	

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js" charset="UTF-8"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="http://www.plupload.com/plupload/js/plupload.full.min.js" charset="UTF-8"></script>
<script type="text/javascript" src="http://www.plupload.com/plupload/js/jquery.ui.plupload/jquery.ui.plupload.min.js" charset="UTF-8"></script>

<script>
<cfoutput>var formid = '#session.formid#';</cfoutput>
$(function() {
    $("#uploader").plupload({
        runtimes : 'html5,flash,silverlight,html4',
        url : "actionpage.cfm?formid="+formid,
        max_file_size : '6mb',
        chunk_size: '0',
        resize : {
            width : 200,
            height : 200,
            quality : 100,
            crop: true 
        },
        filters : [
           {title : "File Types", extensions : "png,jpg,gif"}
        ],
        rename: true,
        sortable: true,
        dragdrop: true,
        views: {
            list: true,
            thumbs: true, 
            active: 'thumbs'
        },
        flash_swf_url : 'assets/js/Moxie.swf',//set this path to where this files is
        silverlight_xap_url : 'assets/js/Moxie.xap',//set this path to where this files is
		init : {
	        FilesAdded: function(up, files) {
	          up.start();
			  $('#filelist').val( $('#filelist').val() + files[0].name + ',');
			  console.log(files[0].name);
	        }
		}
    });	
	
	/************************************/	
	
	$(document).on("click", ".submiter", function() {	
		var data = $('#taskform').serialize();
		$.ajax({
			type: 'post',
			data: data,	
			url: 'actionpage.cfm',
			success: function(result) {
				$('#taskform')[0].reset();
				console.log('success');				
			}
		});        
	});
	
});
</script>
</CFPROCESSINGDIRECTIVE>

Open in new window


****************************************************
Action Page - actionpage.cfm
****************************************************

<cfif StructKeyExists(url,"formid")>
	<cfscript>
		if(! directoryExists(expandPath("/uploads/") & url.formid)) {
			directoryCreate(expandPath("/uploads/") & url.formid);
		}
		if(! directoryExists(expandPath("/uploadchunks/") & url.formid)) {
			directoryCreate(expandPath("/uploadchunks/") & url.formid);
		}
	   source = "/uploadchunks/" & url.formid & "/";
	   destination = "/uploads/" & url.formid & "/";
	   filename = form.name;
	   
	    if ( isNull( form.chunks ) ) {
	        fileMove(
	            form.file,
				expandPath(variables.destination & variables.filename)
	        );
	    } else {       
	        upload = fileOpen( expandPath( variables.source & form.name ), "append" );
	        fileWrite( upload, fileReadBinary( form.file ) );
	        fileClose( upload );
	        if ( form.chunk == ( form.chunks - 1 ) ) {
	            fileMove(
	                expandPath(variables.source & form.name),
					expandPath(variables.destination & variables.filename)
	            );
	        }
	    }		
	</cfscript>
<cfelseif StructKeyExists(form,"filelist")>
	
	<!--- this is where form is submitted to - put all your stuff in this leg of this cfif block --->
	<!--- delete the formid folders at this point along with the source files --->
	
</cfif>

<!--- Reset the content buffer. --->
<cfcontent
    type="text/plain"
    variable="#charsetDecode( 'success', 'utf-8' )#"
    />

Open in new window

0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41795867
Eric - btw you don't need session.formid - change it to variables.formid ...
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41795958
I came up with this solution. the upload works fine the only issue I have is saving the file name into dataabse

$("#uploader").plupload({
        // General settings
        runtimes: 'html5,flash,silverlight,html4',

        // Fake server response here
         url : '/includes/upload.cfc?method=upload',
        //url: "/echo/json",

        // Maximum file size
        max_file_size: '1000mb',

        // User can upload no more then 20 files in one go (sets multiple_queues to false)
        max_file_count: 20,

        chunk_size: '5mb',

        // Resize images on clientside if we can
        resize : {
            width: 200,
            height: 200,
            quality: 90,
            crop: true // crop to exact dimensions
        },

         FileUploaded: function(up, files) {
                var new_file_field = '<input type="hidden" name="'+files.id+'" value="'+files.name+'" />';
                //alert(new_file_field);
                $('form').append(new_file_field);
         },


        // Specify what files to browse for
        filters: [
            { title: "Image files", extensions: "jpg,gif,png" },
            { title: "Zip files", extensions:  "zip,avi" },
            { title: "PDF files", extensions:  "pdf" },
        ],

        // Rename files by clicking on their titles
        rename: true,
        file_data_name: "file",
        multi_selection: false,
        multipart: true,

        // Sort files
        sortable: true,

        // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
        dragdrop: true,

        // Views to activate
        views: {
            list: true,
            thumbs: true, // Show thumbs
            active: 'thumbs'
        },



        // Flash settings
        flash_swf_url : 'http://rawgithub.com/moxiecode/moxie/master/bin/flash/Moxie.cdn.swf',

        // Silverlight settings
        silverlight_xap_url : 'http://rawgithub.com/moxiecode/moxie/master/bin/silverlight/Moxie.cdn.xap'
    });

 $('#taskForm').submit(function (e) {

		e.preventDefault();
		//var uplFile = $('#fileAttached').val();
        var uploader = $('#uploader').plupload('getUploader');
        var forms=($(this).serialize());

        if (uploader.files.length > 0) {
            for(var i=0; i<uploader.files.length; i++){
                var fileUploaded = uploader.files[i].name;
           };
        }



           if ($('#uploader').plupload('getFiles').length > 0) {
                uploader.bind('UploadProgress', function (response){


            // When all files are uploaded submit form
            $('#uploader').on('complete', function(response) {
            	 $.ajax({
                    type: 'POST',
                    url: '/includes/task.cfc?method=addEditTask',
                    data: forms + '&fileUploaded=' + fileUploaded,
                    cache:false,
                    /*contentType:"application/json; charset=utf-8",*/
                    success: function () {
                      $.get('/includes/task.cfc?method=getTasks&taskOwner=<cfoutput>#session.userKey#</cfoutput>',
                        function (result) {
                             $("#taskListing").html(result);
                              $("#dialog").html('');
                             $("#dialog").dialog( "destroy" );
                             $("#dialog").dialog('close');

                        }
                      )
                    }
                  });

                });
            });

            $('#uploader').plupload('start');
        } else {
          $.ajax({
                    type: 'POST',
                    url: '/includes/task.cfc?method=addEditTask',
                    data: forms,
                    cache:false,
                    /*contentType:"application/json; charset=utf-8",*/
                    success: function () {
                      $.get('/includes/task.cfc?method=getTasks&taskOwner=<cfoutput>#session.userKey#</cfoutput>',
                        function (result) {
                             $("#taskListing").html(result);
                             // $("#dialog").html('');
                            // $("#dialog").dialog( "destroy" );
                             //$("#dialog").dialog('close');

                        }
                      )
                    }
                  });
        }

return false;
    });

Open in new window


<cfcomponent>

    <cffunction name="upload" access="remote" returntype="struct" returnformat="json" output="false">
        <cfscript>
            var uploadDir = expandPath('../') & 'upload/fleet/'; // should be a temp directory that you clear periodically to flush orphaned files
            var uploadFile =  uploadDir & arguments.NAME;
            var response = {'result' = arguments.NAME, 'id' = 0};
            var result = {};
            // if chunked append chunk number to filename for reassembly
            if (structKeyExists(arguments, 'CHUNKS')){
                uploadFile = uploadFile & '.' & arguments.CHUNK;
                response.id = arguments.CHUNK;
            }
        </cfscript>

        <!--- save file data from multi-part form.FILE --->
        <cffile action="upload" result="result" filefield="FILE" destination="#uploadFile#" nameconflict="overwrite"/>

    <cfscript>
        // Example: you can return uploaded file data to client
        response['size'] = result.fileSize;
            response['type'] = result.contentType;
            response['saved'] = result.fileWasSaved;

        // reassemble chunked file
            if (structKeyExists(arguments, 'CHUNKS') && arguments.CHUNK + 1 == arguments.CHUNKS){
                try {
                var uploadFile = uploadDir & arguments.NAME; // file name for reassembled file - if using a temp directory then this should be the final output path/file
                    if (fileExists(uploadFile)){
                        fileDelete(uploadFile); // delete otherwise append will add chunks to an existing file
                    }
                var tempFile = fileOpen(uploadFile,'append');
                    for (var i = 0; i < arguments.CHUNKS; i++) {
                        var chunk = fileReadBinary('#uploadDir#/#arguments.NAME#.#i#');
                        fileDelete('#uploadDir#/#arguments.NAME#.#i#');
                    fileWrite(tempFile, chunk);
                    }
                    fileClose(tempFile);
                }
                catch(any err){
                    // clean up chunks for incomplete upload
                    var d = directoryList(uploadDir,false,'name');
                    if (arrayLen(d) != 0){
                        for (var i = 1; i <= arrayLen(d); i++){
                            if (listFirst(d[i]) == arguments.NAME && val(listLast(d[i])) != 0){
                                fileDelete('#uploadDir##d[i]#');
                            }
                        }
                    }
                    // you could add more error handling and return info from err
                    response = {'error' = {'code' = 500, 'message' = 'Internal Server Error'}, 'id' = 0};
                }
            }
    </cfscript>

        <cfreturn response/>
    </cffunction>

</cfcomponent>

Open in new window

0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41796230
looks good Eric
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41796252
is there a way I can only allow a single file to be uploaded through the plupload
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41796441
ok so do something like
if(uploader.files.length > 1)
then cancel the submit and display a message telling user to remove file(s) ...

unfortunately there is not a plupload function that limits number of files for the html5 runtime
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41796553
can I preloadthe images. For example, I just uploaded an image for the task and then decided to come back for the task and see what is been uploaded
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41796578
? well if thats what you want to do
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41809072
Where are you at with this Eric?
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41809156
done with upload . Now dealing with renaming the file that need to be uploaded to have a unique name
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41809161
cool - so ready to close the question?
:)
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41809204
Almost
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41809207
and?
0
 
LVL 19

Author Closing Comment

by:erikTsomik
ID: 41809280
Great advice
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41809305
Thanks for the points and good luck with the project!
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41813084
I just have  noticed when Uploading the files and submitting to the database the upload and ajax request happening 2 times. When I do not upload the file only once. it seems like plupload initiate a second call.

 $(function () {

    $("#uploader").plupload({
        // General settings
        //runtimes: 'html5,flash,silverlight,html4',
 		runtimes: 'html4',
        // Fake server response here
         url : '/includes/upload.cfc?method=upload',
        //url: "/echo/json",

        // Maximum file size
        max_file_size: '1000mb',

        // User can upload no more then 20 files in one go (sets multiple_queues to false)
        max_file_count: 1,

        chunk_size: '10mb',

        // Resize images on clientside if we can
        resize : {
            width: 200,
            height: 200,
            quality: 90,
            crop: true // crop to exact dimensions
        },

         FileUploaded: function(up, files) {
                var new_file_field = '<input type="hidden" name="'+files.id+'" value="'+files.name+'" />';
                //alert(new_file_field);
                $('form').append(new_file_field);
         },


        // Specify what files to browse for
        filters: [
            { title: "Image files", extensions: "jpg,gif,png" },
            { title: "PDF files", extensions:  "pdf" },
        ],

        // Rename files by clicking on their titles
        rename: true,
        file_data_name: "file",
        multi_selection: false,
        multipart: true,

        // Sort files
        sortable: true,

        // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
        dragdrop: true,

        // Views to activate
        views: {
            list: false,
            thumbs: false, // Show thumbs
            active: 'thumbs'
        },



        // Flash settings
        //flash_swf_url : 'http://rawgithub.com/moxiecode/moxie/master/bin/flash/Moxie.cdn.swf',

        // Silverlight settings
       // silverlight_xap_url : 'http://rawgithub.com/moxiecode/moxie/master/bin/silverlight/Moxie.cdn.xap'
    });



$('#taskForm').validator().on('submit', function (e) {

 if (e.isDefaultPrevented()) {

 }else{
		e.preventDefault();
		//var uplFile = $('#fileAttached').val();
        var uploader = $('#uploader').plupload('getUploader');
        var forms=($(this).serialize());

        if (uploader.files.length > 0) {
            for(var i=0; i<uploader.files.length; i++){
                var fileUploaded = uploader.files[i].name;
           };
        }



           if ($('#uploader').plupload('getFiles').length > 0) {
                uploader.bind('UploadProgress', function (response){


            // When all files are uploaded submit form
            $('#uploader').on('complete', function(response) {
            	 $.ajax({
                    type: 'POST',
                    url: '/includes/task.cfc?method=addEditTask',
                    data: forms + '&fileUploaded=' + fileUploaded,
                    cache:false,
                    /*contentType:"application/json; charset=utf-8",*/
                    success: function () {
                      $.get('/includes/task.cfc?method=getTasks&taskOwner=<cfoutput>#session.userKey#</cfoutput>',
                        function (result) {
                             $("#taskListing").html(result);
                              $("#dialog").html('');
                             $("#dialog").dialog( "destroy" );
                             $("#dialog").dialog('close');
							//return false;
                        }
                      )
                    }
                  });

                });
            });

            $('#uploader').plupload('start');

            return false;
        } else {
          $.ajax({
                    type: 'POST',
                    url: '/includes/task.cfc?method=addEditTask',
                    data: forms,
                    cache:false,
                    /*contentType:"application/json; charset=utf-8",*/
                    success: function () {
                      $.get('/includes/task.cfc?method=getTasks&taskOwner=<cfoutput>#session.userKey#</cfoutput>',
                        function (result) {
                             $("#taskListing").html(result);
                              $("#dialog").html('');
                             $("#dialog").dialog( "destroy" );
                             $("#dialog").dialog('close');

                        }
                      )
                    }
                  });
        }
}
return false;
    });

<form class="form-horizontal" role="form" id="taskForm"  method="POST" enctype="multipart/form-data" data-toggle="validator">

 <div class="form-group">

         <div id="uploader" class="uploader">

        <a id="selectFiles" href="##">

            <span class="label">
                Select Files
            </span>

            <span class="standby">
                Waiting for files...
            </span>

            <span class="progress">
                Uploading - <span class="percent"></span>%
            </span>

        </a>

    </div>

    </div>
  </form>

Open in new window

0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41813121
That's one of the issues I was talking about when I said to forget doing the upload based on a click event of a button.

Just let it upload as soon as a file is added or use the plupload upload button ...
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41813127
But then I would like to know what the file name is so I can pass it to the ajax so it can be recorded into the database
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41813128
How would I change the code to do that
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41813144
I just took another look am actually not doing the event based off the button click
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41813167
Submit function rather ...
I showed in the code how to send file names with.
I'm on my phone right now so I'm not posting code ...
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41815288
Can you post the code . I really need to get it resolved
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41815291
It's in the post you selected as the correct answer above
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41815316
I just tried this. But the form does not get submitted
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41816606
It is still doing double submit. May be the problem I am opening the upload page in the jquery dialog . And then once submitted into the database reloading the page again that when I clicking on the post button again I get duplicate submittion

  $(document).on("click", "##btnSubmit", function(e) {
                 	e.preventDefault();
			        var forms = $('##submitCommnets').serialize();

			        var taskid = <cfoutput>#getTasks.taskID#</cfoutput>;
                    var user = <cfoutput>#arguments.taskOwner#</cfoutput>;
					 $.ajax({
				        type: 'post',
				        cache:false,
				        url: '/includes/task.cfc?method=postComments',
				        data: forms,
				        success: function () {


				          $("##viewTask").html("");
				          $(this).unbind('click');
				          //$('##viewTask').dialog("destroy");
				          $("##viewTask").load('/includes/task.cfc?method=viewTask&taskID='+taskid+ '&taskOwner=' + user);
				          e.preventDefault();
				          return false;
				        }
				    });
					return false;
			    });

Open in new window

0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41816724
Look at the accepted solution.
That is a completely working model that does not submit twice.
I imagine what you're doing is you've altered it somehow to make it more like what you had wanted but it's that alteration that is calling it the old way still and making it submit twice.
Just start exactly from what I posted in acceptance solution.
0
 
LVL 19

Author Comment

by:erikTsomik
ID: 41816742
I found the cure for the problem by adding e.stopImmediatePropagation();

How can I get the name of the file that was uploaded. Not the name when I upload the file, but the name that was uploaded to the server. My upload allows unique name, SO first upload was text1 the second automatically will be text2 even though I am uploading the file with the same name
0
 
LVL 24

Expert Comment

by:dgrafx
ID: 41817033
It was 98 degrees in Playa Vista today so was at the beach!!!

Use Pluploads unique filename setting - add this in the settings:
unique_names: true,

Then in the accepted answer code above change this:
$('#filelist').val( $('#filelist').val() + files[0].name + ',');

To this:
 $('#filelist').val( $('#filelist').val() + files[0].id + ',');
to get the unique filename. You can then rename again to something else if you want.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Recently while working on a project I got a very annoying cfdocument has no body error message. I had never seen this error before. So I checked the code. The code was pretty simple; it was Just showing me the cfdocumnt tag and inside that tag a …
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now