I am using SWFuploader with Jquery and PHP(Zend framework) for uploading
http://code.google.com/p/swfupload/
I am facing a problem while using sessions.
There is 3 step login wizard, 1st step is simple form and uplaoder is on 2nd step.
Flow of application is, It stores 1st step data in session after submitting and redirect to 2nd step. When I try to upload some files and try to use data stored in session, it gives me nothing.
I am using this code :
JS Code
var settings = {
flash_url : "/javascript/flash/swfupload.swf",
upload_url: "/login/uploaditems",
post_params: {
'session' : <?php echo session_id;?>
},
file_size_limit : "1 MB",
file_types : "*.pdf;",
file_types_description : "All Files",
file_upload_limit : 100,
file_queue_limit : 10,
custom_settings : {
cancelButtonId : "cancelBtn"
},
debug: false,
button_image_url: "/images/chooseButton-2.png",
// The event handler functions are defined in handlers.js
file_queued_handler : fileQueued,
file_queue_error_handler :fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_start_handler : uploadStart,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
queue_complete_handler : queueComplete // Queue plugin event
};
Swfu1 = new SWFUpload(settings);
PHP Code :
if(isset($params['session'])) {
session_id($params['session']);
}
$uploadedFilesSession = new Zend_Session_Namespace('uploadedFiles'.$params['session']);
if(!isset($uploadedFilesSession->files))
{
$uploadedFilesSession->files = array();
}
if(!isset($uploadedFilesSession->files[$flag])){
$uploadedFilesSession->files[$flag] = array();
}
Everytime it goes in condition !isset($uploadedFilesSession->files) and reset my authentication session too. It is only happening in Safari.
Please guide me.
Related
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);
});
i have been trying so hard to fix my issue. I've looked on google loads and attempted the fixes but i am having no luck at all.
$(function() {
$("#listing_pic").uploadify({
height : 30,
swf : 'uploadify/uploadify.swf',
uploader : 'uploadify/uploadify.php',
width : 120,
fileExt : '*.jpg; *.jpeg; *.JPG; *.JPEG;',
checkExisting : 'uploadify/check-exists.php',
simUploadLimit: 2,
fileSizeLimit : '4MB',
auto : true,
multi : true,
onComplete : function(event,queueID,fileObj,response,data) {
$('#hiddenlistingpic').val(response);
},
});
});
Im trying to get Uploadify to upload my image to my server (which works fine) but then send the filename to the hidden field so that i can post the data into my database update class. It's giving me a headache, and im more than certain its a simple fix.
from here: https://stackoverflow.com/a/3466188/1253747
$(function() {
$("#listing_pic").uploadify({
height : 30,
swf : 'uploadify/uploadify.swf',
uploader : 'uploadify/uploadify.php',
width : 120,
fileExt : '*.jpg; *.jpeg; *.JPG; *.JPEG;',
checkExisting : 'uploadify/check-exists.php',
simUploadLimit: 2,
fileSizeLimit : '4MB',
auto : true,
multi : true,
onComplete : function(event,queueID,fileObj,response,data) {
$('#hiddenlistingpic').val(fileObj.name);
},
});
});
or from the uploadify docs, there seems to be many other ways to get it:
'onUploadSuccess' : function(file, data, response) {
$('#hiddenlistingpic').val(file.name);
}
same thing can be done with the onuploadcomplete.
or is there anything else that i am missing?
I'm lost here. I'm trying to set up a simple file upload, handled by SWFUpload. After file selection nothing happens. I don't see a request being sent, and there is nothing in my console. Is the swf object supposed to call my upload_url page immediately?
var swfu,jobForm;
var j = jQuery.noConflict();
j(window).load(function() {
jobForm = j('.admin-atomic-form form');
swfu = new SWFUpload({
upload_url : "URL/upload.php",
flash_url : "URL/swfupload.swf",
file_size_limit : "20 MB",
file_types : "*.doc;*.pdf;*.rtf;*docx;*.jpg;",
//file_types_description : "All Files",
file_upload_limit : "1",
button_placeholder_id : "swfuploader",
button_image_url : "URL/file-browse.png",
button_width: 100,
button_height: 30,
upload_start_handler : uploadStart,
upload_success_handler : uploadSuccess
});
//jobForm.form.submit(function(ev){ev.preventDefault()})
});
function uploadStart(){
//.submit()
console.log(this,'start');
};
function uploadSuccess(){
//form.submit()
console.log('success');
}
starting to upload a file is a two step process: 1. you select a file (which then populates a path in an input box), 2. you must submit the form to begin the actual upload.
I'm assuming you're not doing step 2, since in your code, you have commented out form.submit()
please uncomment this line: //jobForm.form.submit(function(ev){ev.preventDefault()})
then after you select a file, submit the form.
SWFUploadObj.startUpload(); needs to be fired and that's what initiated the POST request to the specified upload_url. If this method is fired by some default setting, it certainly wasn't doing it for me.
Here is an example of a few of my functions:
// Bound to file_queued_handler : sets a flag that there is a file waiting to upload
function swfuFileQueued(file){
resumeQueued = true;
$j('#browseFile').val(file.name);
}
//Bound to form submit event:
//a successful upload will submit this form again once the success response with the server-moved and renamed filename comes back from the file upload handling script
function swfuFormSubmit(ev){
if(uploadSuccess){
return true;
} else {
if(resumeQueued == true){
ev.preventDefault();
swfuUploadStart(); // see next function
} else {
return true;
}
}
}
function swfuUploadStart(){
try {
swfu.startUpload(); // <-- The actual method that begins the file upload request
} catch (e) {
}
return false;
}
function swfuProgress(){ ...
function swfuError(){ ...
function swfuSuccess(){
//update input element containing filename or id to send with form
//update a status box with "Success"
//uploadSuccess = true
//form.submit() once more, this time uploadSuccess will tell the function to continue on and actually submit itself
Useful URL to understand SWFUpload process : http://www.dconstructing.com/2010/07/08/making-swfupload-work
I am trying to solve a problem with plupload where i show an error in the upload window, generated by upload.php. No matter what i do, i am not able to create the error icon in the window. Although the alerts work fine, the file is always marked as success. Can someone please tell me what am i doing wrong here?
The error from my upload.php is die('{"jsonrpc" : "2.0", "error" : {"code": 500, "message": "File upload failed."}, "id" : "id"}');
And this is the javascript:
// Convert divs to queue widgets when the DOM is ready
$(function() {
// Setup html5 version
$("#html5_uploader").pluploadQueue({
// General settings
runtimes : 'html5',
url : 'upload.php',
max_file_size : '2000mb',
chunk_size : '1mb',
unique_names : false,
// Specify what files to browse for
filters : [
{title : "Video Clips", extensions : "mov,avi,mpg,flv,mp4"},
{title : "Audio Files", extensions : "mp3,wav"},
{title : "Executable Files", extensions : "exe"},
{title : "Zip Files", extensions : "zip,rar"}
],
preinit: attachCallbacks
});
// attach callbacks for FileUploaded and Error
function attachCallbacks(uploader) {
uploader.bind('FileUploaded', function(up, file, response) {
response = jQuery.parseJSON( response.response );
alert(response.error.code);
if (response.error.code == '500') {
alert (response.error.message);
//alert (file.id);
$('#' + file.id).attr('class', 'plupload_failed').find('a').css('display', 'none').attr('title', response.error.message);
file.status = plupload.FAILED;
} else {
alert("yoohoo");
$('#' + file.id).attr('class', 'plupload_done').find('a').css('display', 'none').attr('title', 'Success');
file.status = plupload.DONE;
}
});
}
});
Thanks.
In case anyone else is looking for the solution to this, it's here: http://www.plupload.com/punbb/viewtopic.php?id=1710
The problem is that you're using the FileUploaded event inside the preinit section. You should bind your event on the init section.
(answer from LeandroJF)
Hello I'm using Uploadify to upload photos.
When user is logged, his ID is stored in session, but after uploading anything by Uploadify, his ID is deleted from session, so it looks like he is not logged in.
I tried to pass his ID with session ID and session name as scriptData, but it did not work either. When user is logged in and tries to upload sth, after upload session is clean (there is no user ID and uploaded photo name stored).
When the user is not logged in, session contains uploaded photo name...
Here is the .js:
$(document).ready(function() {
$('#fileUpload').uploadify({
'uploader' : '{/literal}{$PATH_TO_ROOT}{literal}scripts/js/uploadify/uploadify.swf',
'script' : '{/literal}{$URL_PREFIX}{$tc->get('uploadify')}{literal}',
'scriptData' : {'PHP_SESS_ID': '{/literal}{$sessionId}{literal}','PHP_SESS_NAME':'{/literal}{$sessionName}{literal}'{/literal}{if $user},'PHP_SESS_UZIV':'{$user->get('Id')}'{/if}{literal}},
'cancelImg' : '{/literal}{$PATH_TO_ROOT}{literal}scripts/js/uploadify/cancel.png',
'fileDataName' : 'Filedata',
'fileExt' : '*.jpg;*.gif;*.png',
'fileDesc' : 'Image Files',
'sizeLimit' : 5242880, // 5x1024x1024 bytes
'auto' : false,
'buttonText' : 'VYBERTE FOTKU',
'buttonImg' : '{/literal}{$PATH_TO_ROOT}{literal}scripts/js/uploadify/uploadify-butt-{/literal}{$lang}{literal}.jpg',
'rollover' : true,
'width' : 300,
'height' : 45,
'hideButton' : false,
'method' : 'post',
'multi' : false,
'onAllComplete' : function(event,data) {
window.location.href = '{/literal}{$URL_PREFIX}{$tc->get('photo-uploaded')}{literal}';
}
});
});
Here is the backend script:
if (!empty($_FILES)) {
$session_id = $_POST["PHP_SESS_ID"];
$session_name = $_POST["PHP_SESS_NAME"];
session_id($session_id);
session_name($session_name);
if (isset($_POST["PHP_SESS_UZIV"])) {
$user_id = $_POST["PHP_SESS_UZIV"];
$_SESSION['sess_us_id'] = $user_id;
}
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = dirname(dirname(__FILE__)) . '/img/';
$newName = time() . '_' . StripAccent($_FILES['Filedata']['name'], '', false, false);
$targetFile = str_replace('//','/',$targetPath) . $newName;
$savePic = savePic($targetPath, $newName, -590, -500, 100, $tempFile);
$saveThumb = savePic($targetPath, getThumbName($newName), -185, -142, 100, $targetFile);
$_SESSION['uploadedPhoto'] = $newName;
}
Thanks for help
EDIT: Well I've found out this code works on one, but not the other server...
This worked for me:
in your code which display file upload button:
<?php
session_start();
?>
....
$(function() {
$('#file_upload').uploadify({
'formData' : {
'PHPSESSID': '<?=session_id()?>'
},
'buttonText' : 'Upload',
'displayData': 'speed',
'swf' : 'uploadify.swf',
'uploader' : 'uploadify.php',
'onUploadSuccess' : function(file, data, response) {
....
}
});
});
and on uploadify.php
just do this:
session_id($_POST['PHPSESSID']);
session_start();
and that's it, all session data will be accessible in uploadify.php.
Works for me.
Hope I helped someone.
What exactly are you using to generate this Javascript?
'scriptData' : {'PHP_SESS_ID': '{/literal}{$sessionId}{literal}','PHP_SESS_NAME':'{/literal}{$sessionName}{literal}'{/literal}{if $user},'PHP_SESS_UZIV':'{$user->get('Id')}'{/if}{literal}},
Is this being echoed out from PHP? Where is $sessionID, $user, $PATH_TO_ROOT etc... being defined?
Is there a session_start() executed somewhere before your sample upload handling code starts up? Without that, all your session manipulation will be gone when the script exits. You must call session_start() for PHP to preserve $_SESSSION for you.
Make sure that Uploadify is actually getting the proper session names/ID - if it's getting them wrong, then your code will reset the session id/name to something other than what the real session is, and you'll end up with the symptoms you have - vanishing upload data - because it went into some OTHER session.
As well, you don't seem to have ANY error handling in your script and assume the upload succeeded. At bare minimum you should have:
if ($_FILES['Filedata']['error'] === UPLOAD_ERR_OK) {
... process upload ...
} else {
die("Upload failed with error code #" . $_FILES['Filedata']['error']);
}
Just because the _FILES array isn't empty doesn't mean an upload succeeded. PHP will still fill in as much information as it can about the upload, INCLUDING the error code, which means there will ALWAYS be data in that array, regardless of the upload's success/failure.
Do you happen to be testing this with Internet Explorer?
http://www.uploadify.com/documentation/uploadify/using-sessions-with-uploadify/
$('#file_upload).uploadify({
// Your normal options here
formData : { '<?php echo session_name();?>' : '<?php echo session_id();?>' }
});
In Uploadify:
//uploadify.php
$session_name = session_name();
if (!isset($_POST[$session_name])) {
exit;
} else {
session_id($_POST[$session_name]);
session_start();
}