YUI 3 Uploader isuse in IE - php

I am using YUI 3 Uploader.
I take this example from given reference url:
http://yuilibrary.com/yui/docs/uploader/uploader-multiple.html
I have IE.8 version.
I have created a php file say test.php and written the script from the given url as
given below:
<script src="http://yui.yahooapis.com/3.8.1/build/yui/yui-min.js"></script>
<script>
YUI({filter:"raw"}).use('uploader', function(Y) {
Y.one("#overallProgress").set("text", "Uploader type: " + Y.Uploader.TYPE);
if (Y.Uploader.TYPE != "none" && !Y.UA.ios) {
var uploader =
new Y.Uploader({width: "250px",
height: "35px",
multipleFiles: true,
swfURL: "http://localhost.com /test/flashuploader.swf?t=" + Math.random(),
uploadURL: "http://localhost.com/test/test.php",
simLimit: 2,
withCredentials: false
});
});
When I open this page in the IE, nothing happens, no file dialog box opens to select file.
If anyone has already fixed this issue, please suggest me how can i solve?
Thanks,

I have used all source code from below url:
http://yuilibrary.com/yui/docs/uploader/uploader-multiple.html
and
<script src="http://yui.yahooapis.com/3.8.1/build/yui/yui-min.js"></script>
to create instance the uploader.
We need to just replace another version file of yui-min.js file as below
<script src="http://yui.yahooapis.com/3.5.1/build/yui/yui-min.js"></script>
Apart from js file we need to change these
swfUrl: http://mudomain.com/test/flashuploader.swf
UploadeUrl: http://mudomain.com/test/uploader.php
To Upload file on the server, just write the script in the given above page in
the uploadUrl "uploader.php" as
<?php
$uploadedPath = 'Uploaded_Files/';
foreach ($_FILES as $fieldName => $file) {
move_uploaded_file($file['tmp_name'], $uploadedPath.$file['name']);
}
?>
Now you will see all selected files will be uploaded.
But there is limitation in the IE, We can upload 1 to 5 files at a time.

Related

How do we access file blobs in the server?

I am using Blueimp File Uploader.
While uploading files larger than the maxChunkSize, how do we access each uploaded file blobs separately in the server ?
My issue is that I need to forward the uploaded files in separate blobs to a different server using a backend api.
So far, looking at wiki, for chunks of 1 mb, I have added the following in the js :
$('#fileupload').fileupload({
url: 'server/php/',
maxChunkSize: 1000000 // 1 MB
});
but after upload is completed, I see the full merged file in the server :
server/php/files
How do we access the individual blobs on the server ?
I have not done any changes in the default file server/php/index.php :
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
$upload_handler = new UploadHandler();
and the default UploadHandler class in
server/php/UploadHandler.php
(https://github.com/blueimp/jQuery-File-Upload/blob/master/server/php/UploadHandler.php). File is too big to be placed here.
I tried adding fileuploadchunkdone option, but am unsure, how do we access the file blobs in the server -- that is if it is the right way to do it.
$('#fileupload').fileupload({
url: 'server/php/',
maxChunkSize: 1000000 // 1 MB
})
.on('fileuploadchunkdone', function (e, data) {
console.log('chunkdone')
console.log(e)
console.log(data)
});
chunking upload have 2 requirement
javascript to chunking (split of certain bytes) the file
PHP to save and merge file. commonly use : FILE_APPEND
i dont know what chunk file do you want to get. in client or server?
if you want to get chunk which is will be send, you need check on fileuploadchunksend
if you want to get chunk which is finished uploaded, you need check on fileuploadchunkdone
From your question title, i assume you need to get chunk file which is already uploaded in the server.
so let's we use basic html from this page https://github.com/blueimp/jQuery-File-Upload/wiki/Basic-plugin
HTML
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>
<style>
.bar {
height: 18px;
background: green;
}
</style>
</head>
<body>
<input id="fileupload" type="file" name="files[]" data-url="server/php/" multiple>
<div id="progress">
<div class="bar" style="width: 0%;"></div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/vendor/jquery.ui.widget.js"></script>
<script src="js/jquery.iframe-transport.js"></script>
<script src="js/jquery.fileupload.js"></script>
<script>
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo(document.body);
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .bar').css(
'width',
progress + '%'
);
//console.log(progress);
},
maxChunkSize: 50000 // i prefer 50 Kb, because my file is only 190Kb (4 step)
})
.on('fileuploadchunksend', function (e, data) {
console.log('send');
})
.on('fileuploadchunkdone', function (e, data) {
console.log('done');
console.log(data.result);
//forceerror; wrong javascript function to make error so file upload will stopped. and we can start debugging
})
.on('fileuploadchunkfail', function (e, data) {
console.log('fail');
console.log(data);
})
.on('fileuploadchunkalways', function (e, data) {
console.log('always');
});
});
</script>
</body>
</html>
then we edit the php file: server/php/UploadHandler.php
line 1061
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
$index = null, $content_range = null) {
....
if ($uploaded_file && is_uploaded_file($uploaded_file)) {
// multipart/formdata uploads (POST method uploads)
$path_parts = pathinfo($file_path); //new
$chunkFileName = $path_parts['dirname'].'/'.$path_parts['filename'].'_'. $content_range[1]."_". $content_range[2].".".$path_parts['extension'];//new
if ($append_file) {
file_put_contents($chunkFileName, file_get_contents($uploaded_file));//new
file_put_contents(
$file_path,
fopen($uploaded_file, 'r'),
FILE_APPEND
);
} else {
file_put_contents($chunkFileName, file_get_contents($uploaded_file));//new
move_uploaded_file($uploaded_file, $file_path);
}
} else {
// Non-multipart uploads (PUT method support)
....
full code: https://pastebin.com/3AsHbkqQ (i just add 4 lines to get the chunks)
now lets try the code. i try upload 196kb dummy.png using 50kb chunk. (this will processed in 4 step)
after upload dummy.png file: now you will get 5 files:
dummy.png //full file
dummy_0_49999.png //1st chunk
dummy_50000_99999.png //2nd chunk
dummy_100000_149999.png //3rd chunk
dummy_150000_196064.png //last chunk
Then you can do anything with this chunk
NOTE: from my experience please migrate to plupload instead using blueimp. you can read my comment below your question.

Download file after 10 seconds

I have created a download page that has a link to a file, I would like the file to download automatically after 10 seconds but am unsure of how to do this. The link to the file is stored in a cookie and is accessed on the download page and stored in a $file variable.
The link to the file will be similar to this:
https://cloud1.taccess.co.uk/cloud/uploads/eed376ad76d1f74b597aa2e21121f7e6tantami_cloud_file_580a40c1eff3af7484ef592c10bff10047b373cdc5dfd.pptx?AWSAccessKeyId=AKIAJ56YO6753B2RUT2Q&Expires=1477473886&Signature=mF6Zy1Mqo3HM5g%2B4cSePaXF9vM8%3D
This points to the file and includes the required permissions for the file to be downloaded. So in short, I am looking for a way for this link to be opened after 10 seconds so that the file can be downloaded.
Your tag is PHP. So I assume you want to add some delay for download, I think this
will help you
$filename = "your filename";
header("content-type:application/any specific header"); // set the header
// your content
sleep(10) // will add delay for 10 sec
header("Content-Disposition: attachment; filename=$file_name"); // will download your file
in javascript you could do like this
use heroku api to bring the page
<div id="hidden" style="display:none"></div>
<script type="text/javascript">
$(document).ready(function(){
// var text = 'your url';
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'https://login.yahoo.com/', // like yahoo
function (response) {
var res = response;
$('#hidden').append(res);
});
});
after your page is placed inside hidden div then you could do something like this
setTimeout(function(){
$('#hidden').show();// or fade, css display however you'd like.
}, 1000);
});

POST an image to PHP in AJAX

I would like to send an image to a php file using AJAX.
Here's my JS code:
$.ajax({
type: "POST",
url: "http://website.com/add-image.php",
data: "img=" + img
})
And That's my PHP
<?php
if ( !empty( $_POST["img"] ) )
{
move_uploaded_file( $_POST["img"], "image.png" );
}
?>
but it doen't work.
I also tried to replace move_uploaded_file by imagepng or imagejpg but still no result.
How can I save the image on my server ?
Thanks
If you are just looking to get it working, I recommend Ravishanker Kusuma's Hayageek jQuery File Upload plugin. I don't usually recommend plugins, but this one is excellent. It does almost all the work for you. Why re-invent the wheel?
http://hayageek.com/docs/jquery-upload-file.php
He breaks down the process into four simple steps, that basically look like this:
Look for //1 //2 //3:
<head>
// (1) Load the js files (note that it requires jQuery, which we also load)
<link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://hayageek.github.io/jQuery-Upload-File/jquery.uploadfile.min.js"></script> // (1)
</head>
<body>
<div id="fileuploader">Upload</div> // (2) Create DIV
<script>
$(document).ready(function(){
$("#fileuploader").uploadFile({ // (3) initialize plugin
url:"my_php_processor.php",
fileName:"myfile"
});
});
</script>
</body>
The final (fourth) step is to create a PHP file with same name as specified above in the jQuery code (in this case my_php_processor.php) to receive and process the file:
my_php_processor.php:
<?php
$output_dir = "uploads/";
$theFile = $_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);
Note the relationship between myfile in the PHP ($_FILES["myfile"]), and the filename myfile specified in the jQuery code block.
On the Hayageek web page, study the upload.php example on the Server tab.
Note that you can also pass additional variables to the my_php_processor.php processor file by using dynamicFormData. See this other example:
$("#fileuploader").uploadFile({
url:"my_php_processor.php",
fileName:"myfile",
dynamicFormData: function(){
return {
//my_php_processor.php will receive POST vars below
newSubj: $("#newSubj").val(),
newBody: $("#newBody").val(),
};
},
onSuccess:function(files,data,xhr,pd){
//files: list of files
//data: response from server
//xhr : jquery xhr object
alert(xhr.responseText); //displays data ECHOd by `my_php_processor.php`
}
});
my_php_processor.php:
<?php
$n = $_POST['newSubj'];
$b = $_POST['newBody'];
$uploadedFile = $_FILES["myfile"]["name"];
//etc.
echo 'This will display in the alert box';
jsFiddle Sample Code -
Click on Image Example
If your sending your data using a post,
The data property should be a json:
$.ajax({
type: "POST",
url: "http://website.com/add-image.php",
data: {img: img}
})
Instead of sending the image, the right approach would be to send image in base64 encoded format. On the server side you'll have to decode the base 64 encoded string and save as an image. Follow this link to get a better insight on how to send encoded image.

Can't retrieve variable from php

PHP FILE:
<?php
#Communication with the API
require_once 'api.php';
$cloudkey = new CloudKey($user_id, $api_key);
if(isset($_FILES["FileInput"]) && $_FILES["FileInput"]["error"]== UPLOAD_ERR_OK)
{
//Deleted Code: putting the uploaded files in my server.
if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory.$NewFileName ))
{
$video_file = "/home/george/public_html/q/";
$video_file = $video_file . $NewFileName;
#Sending the video from my server to the cloud server
$res = $cloudkey->file->upload_file($video_file);
#The cloud server will create a link
$source_url = $res->url;
#The cloud server will convert the video very fastly
while(1) {
#Deleted Code: Conversion
if ($asset->status == 'ready') {
# A lot of code. It will convert the videos here and if it succeeds it will stop.
break;
# If the conversion fails, display error
} else if ($asset->status == 'error') {
echo "Error while transcoding the media\n";
}
sleep(1);
}
# Getting the URL of a thumbnail
echo $thumb = $cloudkey->media->get_stream_url(array('id' => $media_id, 'asset_name' => 'jpeg_thumbnail_source'));
}else{
die('error uploading File!');
}
}
else
{
die('Something went wrong!');
}
?>
HTML FILE:
{literal}
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
success: afterSuccess, // post-submit callback
uploadProgress: OnProgress, //upload progress callback
resetForm: true // reset the form after successful submit
};
//function after succesful file upload (when server response)
function afterSuccess()
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO INSERT SOMETHING HERE.
}
//progress bar function
function OnProgress(event, position, total, percentComplete)
{
//DOES NOT INTEREST YOU
});
</script>
{/literal}
<div id="output"></div>
I am using smarty template engine. I have an html upload form that will communicate with a php file progressupload.php where the php file will convert the video (using API services) and brings back a response when it finishes.
When the user uploads the video file, ajax will take over show the percentage (in html), and it will send the file to progressupload.php and when the progressupload.php finishes the conversion it will output everything echoed in the php by simply putting this in the html file (I don't know why): <div id="output"></div>.
WHAT I WANT:
When progressupload.php finishes the conversion, it will generate a thumbnail (screenshot) and store its link in $thumb. I want to retrieve $thumb and show it to the user using jquery.
Now if you look at the HTML Code, afterSuccess() is the function where I want to show the thumbnail to the user:
function afterSuccess()
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO SHOW THE THUMBNAIL HERE.
}
I deleted a lot of unnecessary code that could've distracted you. Remember that I am using smarty template engine, my html file does not end with .php, I cannot echo the variable directly. How can I retrieve the php variable and put it in a jquery method after the variable is created.
I have a suspicion that if you retrieve the variable directly on page load, it will not succeed in getting $thumb since the link needs time to be created (uploading, conversion). How can I retrieve that $thumb?
Assuming that you are using jQuery.ajax();
First parameter in the $.ajax 'success' callback is what returned from the server side.
function afterSuccess( response /** this is what returned from your server **/ )
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO INSERT SOMETHING HERE.
console.log(response); // here you can access your $thumbnail
// below code is untested but it should work
// $("#output").html("<img src='"+response+"' class='thumbnail' />");
}

Codeigniter: TinyMCE image manager dynamic image paths

I have installed TinyMCE into my codeigniter build, and I have included the image manager.
In the image manager plugin (which is saved in the public/assets folder) there is a php config file which defines the image & file path constants.
define('DIR_IMAGES', 'images/path/here'); etc
The problem I have is I need the path to be dynamic depending on some data in the database, such as template_name, but I dont know how to include the right files into the config file so I can view the dynamic info.
So if the user has a template_name saved then I need the path to be
define('DIR_IMAGES', $template_name.'images/path/here');
I have also defined the template_name in a constant in core/MY_Controller.php so if I could access that variable that would be easier than doing a query to the DB but either way will work.
Can someone give me a hand with this, thanks a lot!
I've just custom tinymce image but not using TinyMCE image manager.
but I use the tutorial from the link below.
How-to implement a custom file browser
<!-- Start tinymce custom -->
<script type="text/javascript">
tinyMCE.init({
<!--
your tiny mce init here
--->
<!-- custom file browser callback -->
file_browser_callback : 'myFileBrowser',
});
function myFileBrowser (field_name, url, type, win) {
// this is your dynamic image path
var cmsURL = "<?php echo base_url() ?>admin/media/select_image"; <== you can set as you wish
if (cmsURL.indexOf("?") < 0) {
//add the type as the only query parameter
cmsURL = cmsURL + "?type=" + type;
}
else {
//add the type as an additional query parameter
// (PHP session ID is now included if there is one at all)
cmsURL = cmsURL + "&type=" + type;
}
tinyMCE.activeEditor.windowManager.open({
file : cmsURL
,width : 600
,height : 600
,resizable : "yes"
,inline : "yes"
,close_previous : "yes"
,popup_css : true // Disable TinyMCE's default popup CSS
}, {
window : win,
input : field_name
});
return false;
}
</script>
Add a "data-" attribute to your tinymce element and echo your desired url from there. Then in tinymce activeEditor, access that data- attribute value.
Textarea
<textarea name="description" class="tinymceDescription" data-uploadLink="<?php echo DIR_IMAGES; ?>" ></textarea>
TinyMce
tinymce.init({
// other settings here
//either use this if you are uploading automatically.
images_upload_url: $(tinymce.activeEditor.targetElm).attr("data-uploadLink"),
//or use this if you want to override tinymce auto upload.
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
var uploadLink = $(tinymce.activeEditor.targetElm).attr("data-uploadLink");
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', uploadLink);
xhr.onload = function () {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure(xhr.responseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
}
});
The point here is to show you how i got a dynamic upload url into tinymce from the currently selected tinymce instance. The way you upload is your choice which i hope you know how to handle. But ether way, i have provide both the automatic and custom examples.

Categories