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.
Related
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
}
I am using uploadify in one application. I have successfully implemented it. I got that after complete the upload files, the files' queue bar hide slowly. But I do not want to hide this bar because I am able to understand how many files being uploaded as well as which files. I have tried to write something as
'onUploadComplete' : function() {
$('.uploadify-queue').show();
}
But no luck. Is there any option not hide the queue bar of uploadify.
$('#file_upload').uploadify({
'swf' : '/js/uploadify/uploadify.swf',
'uploader' : '/js/uploadify/uploadify.php',
'method' : 'post',
'formData' : { 'someKey' : 'someValue' },
'auto' : false,
'buttonClass' : 'form-control',
'removeCompleted' : false
});
use removeCompleted : false
Basic idea is to clone original block into another and define own rules of closing:
$('#file_upload').uploadify({
// other options
'onUploadSuccess': function (file, data, response) {
// clone block to another to prevent hidding
var blockOld = $('#' + file.id);
var block = blockOld
.clone()
.removeAttr('id')
.insertAfter(blockOld);
// remove original block
blockOld.remove();
// close block on cancel button click
block.find('.cancel').click(function () {
$(this)
.closest('.uploadify-queue-item')
.fadeOut(function () {
$(this).remove();
})
;
});
}
});
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
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).
<script type="text/javascript">
$(document).ready(function() {
$("#uploadify").uploadify({
'uploader' : 'scripts/uploadify.swf',
'script' : 'scripts/uploadify.php',
'buttonImg' : 'css/btn_browseFiles.png',
'rollover' : 'true',
'wmode' : 'transparent',
'height' : '26px',
'width' : '109px',
'cancelImg' : 'cancel.png',
'folder' : 'uploads',
'queueID' : 'fileQueue',
'simUploadLimit' : '2',
'auto' : true,
'multi' : true,
'onComplete' : function(event, queueID, fileObj, response, data) {
$('#filesUploaded').append('<li><strong>file:</strong> '+fileName+'</li>');
}
});
});
</script>
I want to get the "+fileName+" to echo in PHP so I can pass it in a contact form.
<?php $que = ""; ?>` fill in the blanks
<input type="hidden" name="" value="<?php echo($que); ?>">
Besides doing the following, I don't know of a way to pass Javascript variables to PHP...
<script type="text/javascript>
location.href="thisPage.php?fileName=" + fileName;
</script>
And then you would use PHP to do:
<?PHP $que = $_GET["fileName"]; ?>
If you want to use the text in the filename variable, you will need to pass it to a server request somehow.
It can be done several ways:
cookie
getline variable/query string
post variable (put it in a form element)
If you just want to get it into a value on the current page, you should be able to use javascript to do it:
#('#id_of_element').val(filename);
This is assuming you are using jQuery.
This looks like some sort of uploading flash component. If it is uploading the file to your server, then you should be able to intercept the request and work with it from there.
$trigger('uploadifyComplete',ID,{
'name' : event.currentTarget.name,
'filePath' : getFolderPath() + '/' + event.currentTarget.name,
'size' : event.currentTarget.size,
'creationDate' : event.currentTarget.creationDate,
'modificationDate' : event.currentTarget.modificationDate,
'type' : event.currentTarget.type
},
can you see these?so you can use fileObj.name to get file name.