How pass and receive formData values in Uploadify? - php

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

Related

PHP $_POST not seeing data appended to FormData

Okay so I have an uploader script that I customized and it works great. I have 2 more steps that I need to do for it to be complete and it is beyond my scope and I have read and tried numerous things and still am not getting the results that I want.
Again only code that is releative to my issue will be posted as the code works perfect and does not need any changing with the exception of trying to get a value from AJAX to PHP.
FULL JS FILE BELOW:
jQuery(document).ready(function () {
var img_zone = document.getElementById('img-zone'),
collect = {
filereader: typeof FileReader != 'undefined',
zone: 'draggable' in document.createElement('span'),
formdata: !!window.FormData
},
acceptedTypes = {
'image/png': true,
'image/jpeg': true,
'image/jpg': true,
'image/gif': true
};
// Function to show messages
function ajax_msg(status, msg) {
var the_msg = '<div class="alert alert-'+ (status ? 'success' : 'danger') +'">';
the_msg += '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>';
the_msg += msg;
the_msg += '</div>';
$(the_msg).insertBefore(img_zone);
}
// Function to upload image through AJAX
function ajax_upload(files) {
$('.progress').removeClass('hidden');
$('.progress-bar').css({ "width": "0%" });
$('.progress-bar span').html('0% complete');
var productTestID = "333746240";
var formData = new FormData(this);
formData.append('productTestID',productTestID);
//formData.append('any_var', 'any value');
for (var i = 0; i < files.length; i++) {
//formData.append('img_file_' + i, files[i]);
formData.append('img_file[]', files[i]);
}
$.ajax({
url : "upload.php", // Change name according to your php script to handle uploading on server
type : 'post',
data : formData,
dataType : 'json',
processData: false,
contentType: false,
error : function(request){
ajax_msg(false, 'An error has occured while uploading photo.');
},
success : function(json){
var img_preview = $('#img-preview');
var col = '.col-sm-2';
$('.progress').addClass('hidden');
var photos = $('<div class="photos"></div>');
$(photos).html(json.img);
var lt = $(col, photos).length;
$('col', photos).hide();
$(img_preview).prepend(photos.html());
$(col + ':lt('+lt+')', img_preview).fadeIn(2000);
if(json.error != '')
ajax_msg(false, json.error);
},
progress: function(e) {
if(e.lengthComputable) {
var pct = (e.loaded / e.total) * 100;
$('.progress-bar').css({ "width": pct + "%" });
$('.progress-bar span').html(pct + '% complete');
}
else {
console.warn('Content Length not reported!');
}
}
});
}
// Call AJAX upload function on drag and drop event
function dragHandle(element) {
element.ondragover = function () { return false; };
element.ondragend = function () { return false; };
element.ondrop = function (e) {
e.preventDefault();
ajax_upload(e.dataTransfer.files);
}
}
if (collect.zone) {
dragHandle(img_zone);
}
else {
alert("Drag & Drop isn't supported, use Open File Browser to upload photos.");
}
// Call AJAX upload function on image selection using file browser button
$(document).on('change', '.btn-file :file', function() {
ajax_upload(this.files);
});
// File upload progress event listener
(function($, window, undefined) {
var hasOnProgress = ("onprogress" in $.ajaxSettings.xhr());
if (!hasOnProgress) {
return;
}
var oldXHR = $.ajaxSettings.xhr;
$.ajaxSettings.xhr = function() {
var xhr = oldXHR();
if(xhr instanceof window.XMLHttpRequest) {
xhr.addEventListener('progress', this.progress, false);
}
if(xhr.upload) {
xhr.upload.addEventListener('progress', this.progress, false);
}
return xhr;
};
})(jQuery, window);
});
So the above code is from the .js file. The script uploads multiple selected files, which works fine. From what I have read, in order to get additional values sent to PHP you have to use the .append(), which is what I have done below. I created the var productTestID and gave it a value and then added it to the formData using the append().
My issue is how do I read it in PHP?
I have tried $_POST[productTestID] and get no results at all. I even tried doing an isset() and it comes back not set.
So what do I need to do in my PHP code to read or extract that value? Below is an excerpt from my upload.php file and like I said the file uploads work and this is how they are being accessed.
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$error = '';
$img = '';
$dir = dirname($_SERVER['SCRIPT_FILENAME'])."/". DIR_WS_IMAGES . "upload/";
$extensions = array("jpeg","jpg","png");
foreach($_FILES['img_file']['tmp_name'] as $key => $tmp_name )
Further down in my upload.php file:
//MOVE TO FINAL LOCATION
$uploaded_file = $dir.$file_name;
if (rename($uploaded_file, $uniqueFileName))
{
$productTestID = $_POST['productTestID'];
}
$img .= '<div class="col-sm-2"><div class="thumbnail">';
$img .= '<img src="'.$dir.$file_name.'" />'.$uploaded_file . '<br>' .$fileName.'<br>'.$uniqueFileName.'<br>This Product Id is:';
$img .= $productTestID;
$img .= '</div></div>';
}
Thank You,
Shawn Mulligan

Sending data to Codeigniter controller from UploadiFive

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
}

Uploadify HTTP 302 error and IO error in PHP Codeigniter

I Try to integrate my Codeigniter web with uploadify. its work fine in Chrome and even IE, but getting HTTP 302 error when I run my web in Mozilla firefox. and sometimes its show "IO Error" too, I read this post: 302 and IO uploadify error, but still doesnt have idea what I must to do. maybe more detail/clear guide would be help.
this is my uploadify config in view:
$('#shopfile').uploadify({
'debug':false,
'auto':true,
'swf': '<?= base_url(); ?>file/lib/uploadify/uploadify.swf',
'uploader': '<?= base_url(); ?>my_shop/upload_shopheader',
'cancelImg': '<?= base_url(); ?>file/lib/uploadify/uploadify-cancel.png',
'fileTypeExts':'*.jpg;*.jpeg;*.png;',
'fileTypeDesc':'Image Files (.jpg,.jpeg,.png)',
'fileSizeLimit':'2MB',
'fileObjName':'shopfile',
'buttonText':'Select File',
'multi':false,
'removeCompleted':false,
'onUploadError' : function(file, errorCode, errorMsg, errorString) {
alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
$( ".uploadMessageStr" ).html('<div class="alert alert-danger">The file ' + file.name + ' could not be uploaded: ' + errorString + '</div>');
},
'onUploadSuccess' : function(file, data, response){
//some statement..
}
});
and this is my controller / uploader function code :
public function upload_shopheader(){
if (empty($_FILES['shopfile']['name'])) redirect('my_shop/profile');
$config = $this->avatarUploadConfig();
$this->upload->initialize($config);
$data = array();
if (!$this->upload->do_upload('shopfile')) {
//if upload failed...
$upload_error = $this->upload->display_errors();
$data['message'] = "<div class='alert alert-danger'>Upload Failed. ".$upload_error."</div>";
}
else {
//if upload success...
}
echo json_encode($data);
}
Thanks before.
SOLVED with add session id manually through uploadify.
adding this to uploadify config in view:
'formData' : {'SESSION_ID' : '<?= $this->session->userdata('session_id'); ?>'},
and add this code in beginning of controller function:
//check session..
$sess_id = $this->input->post('SESSION_ID');
if(!isset($sess_id)){
redirect('to_some/page');
}
else{
$this->session->set_userdata(array('session_id' => $sess_id));
}

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.

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