Sending data to Codeigniter controller from UploadiFive - php

I am trying to use UploadiFive to upload some files and, as they are uploaded, add information to a database about them. The user enters some details in a form and then clicks upload, at which point the file is uploaded and the information from the form is added to the database with corresponding file name.
I've got it working uploading files, but I need the form to post every time a file is completed uploading. It's posting the form but I'm struggling to get the file name from the uploaded file. Code below:
The HTML page:
<?php echo form_open_multipart('upload/do_upload', 'id="upload_form" name="upload_form"');?>
<div id="queue"></div>
<input id="file_upload" name="file_upload" type="file" multiple="true">
<div id="target"></div>
</form>
<script type="text/javascript">
<?php $timestamp = time();?>
$(function() {
$('#file_upload').uploadifive({
'auto' : true,
'checkScript' : '<? echo base_url();?>uploadify/check-exists.php',
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5('unique_salt' . $timestamp);?>'
},
'queueID' : 'queue',
'onError' : function(errorType) {
alert('The error was: ' + errorType);
},
'uploadScript' : '<? echo base_url();?>uploadify/uploadifive.php',
'onUploadComplete' : function (event, queueID, fileObj, response, data, file) {
//Post response back to controller
$.post('<?php echo site_url('upload/do_upload');?>', {
field1: $("#field1").val(),
field2: $("#field2").val(),
field3: $("#field3").val(),
field4: $("#field4").val(),
checkbox1: $("#checkbox1:checked").val(),
field5: $("#field5").val(),
filearray : response},
function(info){
$("#target").append(info); //Add response returned by controller
});
}
});
});
</script>
Then my controller:
//Decode JSON returned
$file = $this->input->post('filearray');
$json_decoded = json_decode($file);
// Get the image filename & full filename with path
$image_file = $json_decoded->{'file_name'};
$path = "assets/photos/highres/".$image_file;
echo "IMAGE FILE NAME: " . $image_file; die;
For debugging purposes, I just did an echo of $image_file.
It seems to be submitting everything except the response from the uploadifive.php script. When I use Firebug I can see that I do get a response, and it looks correct, but the response (filearray) isn't being posted to the form to be decoded.
Any ideas as to why I can't get the filename from the response?

TL;DR
Use event.name in onUploadComplete:function(event,data){}
If you really need the server's response, then you might want to use data (unfortunately, I can't test it but the documentation wouldn't lie, would it ?).
The details
The documentation for onUploadComplete tells us the following:
onUploadComplete
Input Type
function
Overridable
N/A
Triggered once for each file upload that completes.
Arguments
file
The file object that was uploaded
data
The data returned from the server-side upload script (echoed in uploadifive.php)
Demo
$(function() {
$('#file_upload').uploadifive({
'uploadScript' : '/uploadifive.php'
'onUploadComplete' : function(file, data) {
alert('The file ' + file.name + ' uploaded successfully.');
}
});
});
This is quite different from what is in your code:
'onUploadComplete' : function (event, queueID, fileObj, response, data, file) {...}
I could not test UploadiFive, but did a quick check with Uploadify:
'onUploadComplete' : function(event) {
console.log(JSON.stringify(event,null,4));
}
Which returned this output:
{
"size": 34405,
"post": {},
"modificationdate": "2015-09-21T02:24:51.597Z",
"name": "Tire-wheel-advisor1.jpg",
"creationdate": "2015-09-21T02:24:51.539Z",
"id": "SWFUpload_0_0",
"type": ".jpg",
"filestatus": -4,
"index": 0
}

Related

Uplodify returns HTTP Error 302 in firefox

I am using uplodify to upload files to my server.
It is working with no issue in Google Chrome. But when I try to upload a file using Firefox I get HTTP Error 302 and the file does not uploaded.
Here is my script
<?php $timestamp = time();?>
$('#file_upload').uploadify({
'formData' : {
'timestamp' : '<?php echo $timestamp;?>',
'token' : '<?php echo md5($timestamp);?>',
'session' : '<?php echo $session->currentSessionID(); ?>',
'upload_path': 'ticketing_center/',
'allowed_extentions': 'jpg,jpeg,gif,PNG,JPG,png,JPEG,pdf,jpeg,zip,rar,doc,docx,csv,xls,xlsx,txt,csv,xml'
},
'auto' : true,
'removeCompleted': true,
'swf' : '../../includes/uploadify.swf',
'onError' : function(event, queueID, fileObj, errorObj) { alert(errorObj.type + ' ' + errorObj.info ); },
'uploader' : '../../includes/uploadify.php',
'fileSizeLimit' : '20MB',
'fileTypeExts' : '*.gif; *.jpg; *.JPG; *.png; *.PNG; *.JPEG; *.pdf; *.jpeg; *.zip; *.rar; *.doc; *.docx; *.csv; *.xls; *.xlsx; *.txt; *.csv; *.xml;',
'onUploadSuccess' : function(file, data, response) {
if(response === true){
$('#attached_files').append('<input type="hidden" class="uploadedFiles" name="attachments[]" value="' + $.trim(data) + '" />');
$('#queue_final').append('<div style="display: block;" class="removeFile" id="' + $.trim(data) + '">(x) ' + file.name + '</div>');
} else {
alert('Invalid File Type');
}
$('.removeFile').click( function(){
var file_name = $(this).attr('id');
$( "#dialog-confirm" ).dialog( "open" ).data('file_name', file_name);;
});
}
});
I have done research prior posting this question but none of the solutions that I found solved my problem.
here is what I have tried so far
I have tried adding the session value to the script a 'session' : '<?php echo $session->currentSessionID(); ?>'
Then in my uploadify.php code I did
if (array_key_exists('session', $_REQUEST))
session_id($_REQUEST['session']);
I tried adding header( " HTTP/1.0 200 OK" ); to the top of my PHP script and that did not work as well.
I have tried to add the onError function to display any error but that is not displaying anything.
I am not sure what else could be causing this? Note that it is working on Chrome with no issues.
Here is a screenshot of the error after trying to upload
I am using Firefox 32.0.3.
My Apache is running in Windows Server 2008 R2 I am not sure if this make a difference.
Flash will not pass through your existing PHP Session information, so if you are getting the 302 error it is likely that your application is returning the login URL to the Flash player. To resolve this issue, you could include the session information in scriptData and manage it manually in your application.

How do I return data via Ajax using Plupload on Upload Complete?

I've been trying for the last few hours to get something... anything back from the pluploader upon completion of the queue to no avail.
Here is my JS code:
var uploader = $('#pluploadDiv').pluploadBootstrap();
uploader.bind("UploadComplete", function(up, files) {
var obj = $.parseJSON(response.response);
alert(obj.result);
});
On the very last line of the upload.php script, I have:
die('{"jsonrpc" : "2.0", "result" : "'.$_REQUEST['unitID'].'", "id" : "id"}');
This makes sense to me... but it's not working, the files upload without problems, but the alert doesn't even fire off... there is no response whatsoever.
Thoughts?
EDIT WITH NEW CODE AS A SOLUTION
The JS that I'm using (thanks jbl):
var uploader = $('#pluploadDiv').pluploadBootstrap();
uploader.bind('FileUploaded', function(upldr, file, object) {
var myData;
try {
myData = eval(object.response);
} catch(err) {
myData = eval('(' + object.response + ')');
}
$("#vehicle_id_value").val(myData.result);
});
Upload.php script stayed the same, last line of code:
die('{"jsonrpc" : "2.0", "result" : "'.$_REQUEST['unitID'].'", "id" : "id"}');
So basically when I create the shell row to associate images to in the upload script, I pass the row ID back to the original form into a hidden input field via the FileUploaded event that is bound to the plupload object.
<input type="hidden" name="vehicle_id_value" id="vehicle_id_value" value="" />
Works like a charm!
Several files could have been uploaded as part of the upload process. The individuals responses are not avalaible anymore when on UploadComplete stage.
If you want to display info about a specific file upload, you should bind to the FileUploaded event instead of UploadComplete.
Something like :
uploader.bind('FileUploaded', function(upldr, file, object) {
var myData;
try {
myData = eval(object.response);
} catch(err) {
myData = eval('(' + object.response + ')');
}
alert(myData.result);
});
Hope this will help
have you tried echo instead of die?
echo '{"jsonrpc" : "2.0", "result" : "'.$_REQUEST['unitID'].'", "id" : "id"}';
function fileupload(fileuploadid, urlashx, foldername, keyid, filelimit, filefilters) {
$("#" + fileuploadid).plupload({
// General settings
runtimes: 'html5,flash,silverlight,html4',
url: urlashx,
//Set parameter for server side
multipart_params: {
foldername: foldername,
keyid: keyid
},
// Maximum file size
max_file_size: filelimit,
// User can upload no more then 20 files in one go (sets multiple_queues to false)
max_file_count: 20,
multiple_queues: true,
//chunk_size: '10mb',
// Resize images on clientside if we can
resize: {
//width: 200,
//height: 200,
quality: 90,
crop: false // crop to exact dimensions
},
// Specify what files to browse for
filters: [
{ title: "Allowed files", extensions: filefilters }
],
// 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',
// Post init events, bound after the internal events
init: {
FileUploaded: function (up, file, jsonMsg) {
var json = JSON.parse(jsonMsg.response); // now I have json object
if (json.success) {
AlertMessage("Message", json.message, "success", "False");
} else {
AlertMessage("Message", json.message, "error", "False");
}
up.splice(); //remove items of container
up.refresh(); //refresh container
}
}
});
}
uploader.bind('FileUploaded', function (up, file, res) {
var res1 = res.response.replace('"{', '{').replace('}"', '}');
var objResponse = JSON.parse(res1);
alert(objResponse.fn);
});

uploadify - show uploaded images on page

I'm building a site (in php) that uses uploadify to allow a user to upload portfolio images.
I have uploadify working fine, but I'm just wondering the best way of showing the uploaded images on the page once they have been uploaded. Is it possible to do without a page refresh?
I've pasted my uploadify code below:
<script>
<?php $timestamp = time();?>
var counter = 1;
$(function() {
$('#file_upload').uploadifive({
onUploadComplete: function(event, queueID, fileObj, reponse, data) {
//alert(counter);
counter = counter +1 ;
},
'buttonText' : 'Upload Images...',
'uploadLimit' : 12,
'uploadScript' : '/includes/uploadifive.php',
'checkScript' : '/includes/check-exists.php',
'auto' : true,
'method' : 'post',
formData : {
'page_id' : '<? echo $pageDetails->row['page_id'] ?>',
'counter' : counter,
'timestamp' : '<? echo $timestamp;?>',
'token' : '<? echo md5('unique_salt' . $timestamp);?>'
},
});
});
</script>
I'm not too sure how to get the file name from uploadify
Sure, you can just add img elements to the page dynamically via the DOM:
var img = document.createElement('img');
img.src = "/path/to/the/new/img.png";
document.getElementById("somecontainer").appendChild(img);
Live Example | Source
You may need to do an ajax call to the server to get the path of the new image, unless that falls out naturally from your application logic.
In the edition I use there is a function
onUploadSuccess : function(file,data,response){
}
Then I can get file name by file.name;
So in your code maybe the fileObj, You can try fileObj.name to get the name of the file you upload.

How pass and receive formData values in Uploadify?

I have been trying to pass and modify data from the client side of uploadify to the server file uploadify.php using the formData setting. I have tried many of the solutions posted on here and the uploadify forums but with no avail.
Initially both formData values are set to the string 'empty' and then when an upload starts, eAlias is set to 2 and eDate to a date. The server script then receives these values by POST and echos them back to the client script which displays this data in an alert (in onUploadSuccess). In all the possible solutions tried the values are either "" or 'empty', ie the setting on the formData keys in onUploadStart doesn't work.
I have included most of the client script and the server script below.
Any help or advice would be greatly appreciated, thank you.
Client-side script:
<script type="text/javascript">
$(document).ready(function()
{
$(".uploadifyfile").uploadify(
{
'swf' : '/xx/uploadify.swf',
'uploader' : '/xx/uploadify.php',
'auto' : true,
'height' : 15,
'method' : 'POST',
'multi' : false,
'uploadLimit' : 10,
'formData' : { 'eAlias' : 'empty', 'eDate' : 'empty' },
'onUploadSuccess' : function(file, data, response)
{
alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ' : ' + data);
document.getElementById("adminForm")[buttonPressed].value = data;
},
'onUploadStart' : function(file)
{
var eventDate = "<?php echo $this->row->dates; ?>";
var eventVenue = 'test';
alert('Venue Alias: ' + eventVenue + '\neventDate: ' + eventDate);
//**** The line below is the one in question ****//
$(".uploadifyfile").uploadify("settings", "formData", {"eAlias": 2, "eDate" : eventDate});
},
'onSelect' : function(event, ID, fileObj)
{
var eid = event.id;
if(eid == "SWFUpload_0_0")
{
window.buttonPressed = "custom01";
alert('1');
}
...
}
});
});
</script>
Server-side script
$targetFolder = '/xx/uploads'; // Relative to the root
if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Set $someVar to 'someValue'
$eventAlias = $_POST['eAlias'];
$eventDate = $_POST['eDate'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo $targetFolder . '/' . $_FILES['Filedata']['name'];
echo ' eventAlias: '.$eventAlias.' eventDate: '.$eventDate;
} else {
echo 'Invalid file type.';
}
}
The problem was as I thought; it was because I was using multiple instances of the uploadify button and referring to them using the .uploadifyfile class. Uploadify doesn't seem to work fully when using classes.
The, probably rudimentary, solution I came up with was to use the 'onSelect' function to store the id of the button pressed into a global variable (window.uploadid) and then use this in the 'onUploadStart' function. Now, for example, when the 2nd button is pressed, the fileType attribute is changed to finalDetails successfully.
I had looked at using jQuery selectors, but they didn't seem to work in this case for id's, just classes.
I've no doubt that there will be several optimisations do be made to the below code, but I hope it will save anyone who was in the same situation as I was many hours of work.
<script type="text/javascript">
$(document).ready(function()
{
$(".uploadifyfile").uploadify(
{
...
'method' : 'post',
'formData' : { 'eventDate' : 'notSet', 'eventVenue' : 'notSet', 'fileType' : 'notSet' },
'onUploadStart' : function(file)
{
var eventDate = "<?php echo $this->row->dates; ?>";
var eventVenue = "<?php echo JFilterOutput::stringURLSafe($this->row->venue); ?>";
$(uploadid).uploadify('settings','formData',{ 'eventDate' : eventDate, 'eventVenue' : eventVenue, 'fileType' : fileType });
},
'onSelect' : function(event, ID, fileObj)
{
alert('event.id:' + event.id);
var eid = event.id; // To determine which button was pressed
if(eid == "SWFUpload_0_0") // Flyer upload
{
window.buttonPressed = "custom01";
window.uploadid = "#file_upload";
window.fileType = "flyer";
}
else if(eid == "SWFUpload_1_0") // Final Details upload
{
window.buttonPressed = "custom02";
window.uploadid = "#file_upload2";
window.fileType = "finalDetails";
}
...
}
});
});
</script>
...
<input type="file" name="file_upload" id="file_upload" class="uploadifyfile" />
...
<input type="file" name="file_upload2" id="file_upload2" class="uploadifyfile" />
your clientSide code is right.i use the same code ,and it works well.so you'd better use id to generate a uploadify instance instead of class

problem with returning the filename using Uploadify

I am using the Uploadify Plugin to upload the picture, and i am doing some operations like
a) when a user upload the file the upload button is removed automatically
b) and the uploadify.php script will rename the file and store it in designated directory.
and here is the code which i am using to perform the action.
Jquery Code :
<script type="text/javascript">
$(document).ready(function() {
$('#fileUpload, #fileUpload2').uploadify({
'uploader': 'img/uploadify.swf',
'script': 'uploadify.php',
'folder': 'upload',
'auto' : 'true',
'cancelImg': 'img/cancel.png',
'fileDesc': 'jpg/jpeg',
'displayData': 'percentage',
'fileExt': "*.jpg;*.jpeg",
'sizeLimit' : '8388608',
'fileDataName' : 'file',
onComplete : function(event, queueID, fileObj, reposnse, data)
{
$('#filesUploaded').append('<a href='+fileObj.filePath+'>'+fileObj.name+'</a><br>');
$("#firstUpload").remove();
}
}); });
</script>
and in the php i have used the combination of date with a unique id to rename the file which is perfectly working fine.
but when i want to view the file name and i do that by calling the div
<div id="filesUploaded"></div>
it shows the original filename and not the renamed file. i tried changing the value from '+fileObj.name+' to '+response+'
i guess the problem is within the above code as the file.Obj.name prints the selected file name and not the processed file, and when i change it to +response+ it uploads the file and rename it but in the form page it does not print the renamed file name. and it freezes with the progress bar composing 100% progress.
how do i make it print the renamed file name.?
thank you
Edit : here is my PHP code .
<?php
include('database.php');
$date = date("dFY");
$query = "SELECT MAX(id) as max_id FROM news";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$max_id = $row['max_id']+1;
echo $max_id;
$file1 = "file_$date"."_$max_id.jpg";
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = 'upload/';
move_uploaded_file($tempFile,$targetPath.$file1);
}
?>
For me this didn't work. I was looking for something similar - this is what worked for me:
'onUploadSuccess' : function(file, data, response) {
alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
}
In my case I used my uploadify.php to create a unique filename - then I used echo $filename - rather than '1'. That way "data" always contains the newest filename.
Cheers
Here's the problem. The Javascript code has a typo. You have written reposnse instead of response in onComplete call. Do it like this:
onComplete : function(event, queueID, fileObj, response, data)
Then when you do the +response+, the script will not hang and will show the MaxID (which you're outputing from the PHP script).

Categories