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));
}
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 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.
I tried many multiple file uploaders which can be integrated with codeigniter like
pulpload
jquery file upload
Even though they work perfectly in the pure php environment, i could not make them work in codeigniter framework. I tried this for two days.. tried many articles which was in the github and blogs..
But i could not made it in codeigniter framework..
If anyone can tell me it by step by step or if there is a tutorial for that, please help me.
I am a newbi to codeigniter..
New:
I downloaded the blueimp Jquery-File-Upload plugin, and followed this link as it is..
https://github.com/blueimp/jQuery-File-Upload/wiki/Latest-jQuery-File-Upload-easy-integration-with-codeigniter
When I select a file and click upload in chrome it says:
Error SyntaxError: Unexpected token <
In firefox it says:
Error SyntaxError: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I examined the difference between using it on my server and on the demo server, on my server in firebug the POST return is the entire index.html...
but on the demo server it returns JSON data..
Here is the modified section of js/main.js that I changed:
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: 'upload/do_upload'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.io') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
});
The only thing I changed was making index.html to have the form action point to my script (upload/do_upload)
controller
function add()
{
if(isset($_POST['submit']))
{
$length = count($_FILES['image']['name']);
$filename = $_FILES['image']['name'];
$tempname = $_FILES['image']['tmp_name'];
$allimage = array();
foreach($filename as $key =>$value)
{
move_uploaded_file($tempname[$key],'media/uploads/mobile_product/'
.$filename[$key]);
$allimage[] = $filename[$key];
}
if(!empty($allimage))
{
$allimage = json_encode($allimage);
}
else
{
$allimage = '';
}
$data['image'] = $allimage;
$this->db->insert('table_name',$data);
$this->session->set_flashdata('message','<div class="alert alert-success">Record has been successfully saved.</div>');
}
}
I'm trying to upload files to GalleryCMS, but I get an HTTP error 500 each time.
I checked every webpage possible, I changed my php.ini, the execution time to 1200, the upload max to 300mb, I changed the sizelimit to 200MB, I tried to change modsecurity in the .htaccess file, the problem was not there.
I am able to upload any file upto 2MB, anything more I get HTTP error 500. Would any of you guys have any new ideas regarding this ? I got dead ends with most of the sites I visited.
Below is my uploadify script (it came along with GalleryCMS, I haven't changed it much, except for the size limit) :
$('#file_upload').uploadify({
'uploader' : '<?php echo base_url(); ?>flash/uploadify.swf',
'script' : '<?php echo base_url(); ?>index.php/api/upload/<?php echo $album->id; ?>',
'cancelImg' : '<?php echo base_url(); ?>images/cancel.png',
'folder' : '/uploads',
'auto' : false,
'multi' : true,
'scriptData' : { 'user_id' : '<?php echo $user_id; ?>' },
'fileExt' : '*.jpg;*.jpeg;*.gif;*.png',
'fileDesc' : 'Image files',
'sizeLimit' : 209715200, // 200MB
'wmode' : 'opaque',
'onSelect' : function(event, ID, fileObj) {
$('#upload-btn').show();
},
'onCancel' : function(event, ID, fileObj) {
$('#upload-btn').hide();
},
'onError' : function(event, ID, fileObj, errorObj) {
},
'onComplete' : function(event, ID, fileObj, response, data) {
var fileName = response;
$('#upload-btn').hide();
$('#new-images').show();
$.ajax({
url : '<?php echo base_url(); ?>index.php/album/resize/<?php echo $album->id; ?>/' + response,
type : 'POST',
cache : false,
success : function(response) {
if (response !== 'failure') {
var new_image = '<li><img src="<?php echo base_url(); ?>uploads/' + response + '" /><br />' + response + '</li>';
$('#new-image-list').append(new_image);
} else {
var fail_message = '<li>Thumbnail creation failed for: ' + fileObj.name + '</li>';
$('#new-image-list').append(fail_message);
}
},
error : function(jqXHR, textStatus, errorThrown) {
alert('Error occurred when generating thumbnails.');
}
});
}
});
To check it by yourself, the url is GalleryMe
username: test#test.com
password: 12345
Since you are using shared hosting, I am pretty sure you are experiencing a problem with your shared host configuration. As tells your phpinfo(); you are using Apache/2 with FastCGI.
I think that the MaxRequestLength of the FastCGI Apache module is set too low by your host provider.
If possible, you need to add this block to your VirtualHost config :
# Work around annoying fcgid limitations
<IfModule mod_fcgid.c>
# 20MB should be enough
MaxRequestLen 20000000
</IfModule>
If not, you have either to contact your provider or to change provider.
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