Changing img src with the fileupload value using jquery/php/html - php

I'm working on a facebook tab that accepts some text and also a picture using an html fileUpload component, the idea is that when the user selects a picture in the fileUpload component, the image they select appears on the page as a way of previewing the picture before uploading it to the server. I tried fectching the image url using val(), but for security reasons, browsers do not give the complete url of a local file. Is there a way to do this using either php or jquery?
Thanks

I believe this is what you're looking for:
function handleFiles(files) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imageType = /image.*/;
if (!file.type.match(imageType)) {
continue;
}
var img = document.createElement("img");
img.classList.add("obj");
img.file = file;
preview.appendChild(img);
var reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
}
}
You might also be interested in reading other examples, like this one.
Edit: This method relies on the FileReader API, so it won't work on IE9 as you've pointed out, but I don't think it is possible otherwise.
At the end of the day, do you need IE9 compatibility ? You might find it acceptable to add a functionality that works for all but a few percent of your user base.

Related

Play Google Drive Video in JW Player And Get Direct Link For Google Drive Video

I want to PLay google drive videos in JW player in my website .I know it is possible because a lot of websites doing this e.g fmovies
Is there any API or piece of code through which i can achieve this URL for google drive video
https://redirector.googlevideo.com/videoplayback?id=4d0be5bc491e2dd7&itag=18&source=webdrive&requiressl=yes&ttl=transient&pl=21&mime=video/mp4&ipbits=0&sparams=api,expire,id,ip,ipbits,itag,mime,mm,mn,ms,mv,pl,requiressl,source,ttl&api=FsxSHTiLgbCln6EzpdilVgW6JQxNqam8I5YPHEFLs3E=&cms_redirect=yes&expire=1499015322&ip=37.187.148.42&mm=30&mn=sn-25ge7ney&ms=nxu&mt=1499000741&mv=m&signature=658276E5F00AAFD155876EC75453507DE10DDEDB.7FAD65986F21E14B5FAFB6E145252310F86A10B6&key=cms1&app=storage
I already tried juicy API but its not working for me
If you just want to stream a video from Google drive then this can be done - you can see a working example here:
https://sourcey.com/html5-video-streaming-from-google-drive/
You can see exactly how it is coded by right clicking and inspecting in your browser
<video controls="controls" style="margin-bottom:20px;width:590px">
<source src="https://drive.google.com/uc?export=download&id=0B0JMGMGgxp9WMEdWb1hyQUhlOWs" type="video/mp4">
</video>
To create a signed URL for Google cloud storage programatically you need to follow their instructions at the link below - I have not copied or summarised them here as, if the similar AWS mechanism is anything to go by, the approach can change often and it is best to always check the latest official documentation:
https://cloud.google.com/storage/docs/access-control/create-signed-urls-program
You can try this Perl script to get the direct download link. If you want to play it in JWPlayer, you'll have to run the script from the server to get the link, then insert that link into the HTML.
https://circulosmeos.wordpress.com/2014/04/12/google-drive-direct-download-of-big-files/
Files hosted at Google Drive service can be shared publicly. Nevertheless, if they’re too big, Google pages advice that “Google Drive can’t scan this file for viruses” and ask the user for confirmation in order to proceed with the download.
If for any reason you’re trying to do an unattended download of the file or downloading it on a resource-limited environment, this will prevent direct use of the link.
Here is the script
https://github.com/circulosmeos/gdown.pl
However, the script downloads the file to the filesystem, so you'll have to modify it so on the last URL re-direct, you save the final URL instead of downloading it.
if you have WordPress Webiste you can use GD Player WordPress Plugin works with Google Drive Mp4 etc.. it can also set subtitles in videos. I use it, and it for me works very well. I hope this helps.
I was trying to do this, I'm able to get the URL, but then there's the problem of streaming it from the server back to the client, basically use puppeteer to go to the URL, click the play button, wait for the video eleemnt to appear, get the "src" attribute, then (somehow over XMLHttpRequest) stream it back to the server, then have the server (nodeJS) stream it back to the client, then use that URL to embed the video (not complete yet see my [very humble] question on it for more):
var puppeteer = require("puppeteer-core");
var http=require("https");
var fs=require("fs");
var fetch=require("fetch-node");
(async() => {
var browser = await puppeteer.launch({
executablePath:"./cobchrome/chrome.exe"
});
console.log("Got browser", browser);
var page = await browser.newPage();
console.log(page,"got page");
await page.goto("https://docs.google.com/file/d/0B9aMNh1shw_4VUVVWkF0TjRHWTA/preview?enablejsapi=1&playerapiid=player4");
console.log("went to page..");
var newClickID = ".ndfHFb-c4YZDc";
var clicker = await page.waitForSelector(newClickID);
await page.click(newClickID);
var frame = await page.waitForSelector("iframe[id=drive-viewer-video-player-object-0]");
var cf = await frame.contentFrame();
await cf.waitFor(() => !!document.querySelector("video"))
var video = await cf.$("video");
var videoEl = await cf.evaluate(
v =>{
var result = {};
for(var k in v) {
result[k] = v[k];
}
return result;
},
video
);
var src = videoEl.src;
await page.goto(src);
console.log("went to video page ", src);
var file = fs.createWriteStream("output/therebbe.mp4");
var count = 0;
page.on("console", c => {
var txt = (c.text()),
buff = Buffer.from(txt,"base64");
// var pic = fs.createWriteStream("output/frame"+count+".png");
// pic.write(buff);
// pic.end();
console.log("Consoling ",count++, buff);
// file.write(buff);
});
await page.evaluate(() => {
function _arrayBufferToBase64( buffer ) {
var binary = '';
var bytes = new Uint8Array( buffer );
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode( bytes[ i ] );
}
return window.btoa( binary );
}
function str2ab(str) {
var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i=0, strLen=str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
var x = new XMLHttpRequest();
var url = location.href;
x.onreadystatechange = function(){
if(x.readyState == 200) {
console.log("done");
} else {
console.log(
_arrayBufferToBase64(
str2ab(x.response)
)
);
}
}
// x.responseType="arraybuffer";
x.open("GET",url,true);
x.send("");
});
// await browser.close();
})();
Just an idea: You don't need JW player or PHP, I's all baked into browsers (HTML5) these days. Here's an example of how to do it (with Google's Material Design UI). Just plain old HTML/CSS/JS.
https://github.com/rhroyston/mdl-audio

Add and delete thumbnail using ajax

I need to create and delete thumbnail image in my yii2 app. I must to have max 5 images and when I was choose files I may to see thumbnails of that images.
I added images in my view with that:
?= $form->field($images, 'imagesFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*','id'=>'gallery-photo-add'])->label(false) ?>
and I can get images in my controller:
$images->imagesFiles = UploadedFile::getInstances($images,'imagesFiles');
How can I see thumbnails? I need to create ajax request? If yes, how I can delete different images? Or add them to my view maybe with some id's.
If you want to see images after choosing them from disk, before submit form, you can preview selected files in view using javascript, eg:
$('#gallery-photo-add').on('change', function() {
var input = $(this)[0];
var images = $('#some-div');
for (var i=0; i<input.files.length; i++) {
if (input.files && input.files[i]) {
var reader = new FileReader();
reader.onloadend = function (e) {
images.append('<img src="'+e.target.result+'" />');
};
reader.readAsDataURL(input.files[i]);
}
}
});

Check Screen Width then all Urls on the page Redirect to mobile if

I am a newbie to jQuery / javascript and I had this working without checking the window size first. Then messed around with it and can not get it to work. The redirect is supposed to replace mysite.com/index.php?querystring with mysite.com/mobile.php?querystring if screen size is less then 699. Please help. Thank You.
This function seems to work exaclty how I need it but need to have onload with if screen size is less then.
$('a').each(function(index, a) {
var href = $(a).attr('href');
$(a).attr('href', 'http://mysite.com/mobile.php?redirect=' + href;)
}
}
//below is not working
function checkWidth() {
var windowSize = $(window).width();
if (windowSize <= 699) {
window.onload = function() {
/* onload code */
// Execute on load
//checkWidth();{
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
anchors[i].href = "http://mysite.com/mobile.php?redirect=" + anchors[i].href
/* function checkWidth() {
var windowSize = $(window).width();*/
}
}
If you intend on using jQuery, this should work:
$(document).ready(function() {
var window_width = $(window).width();
if( window_width < 699 ) {
$('a').each(function(index, a) {
var href = $(a).attr('href');
$(a).attr('href', 'http://mysite.com/mobile.php?redirect=' + href;
});
}
});
This is really something you should be doing server-side. Because someone isn't exactly going to be switching the device over the course of the session, you should check the device when they first visit the site, and then create a session variable storing it. Then, on every new page have the server check the variable and use it to determine which links to put in. If you're content with doing it client-side, though, Ryan Pilbeam's answer should work.

retrieve variables from php and send to a js function via AS3

Can anyone tell me how to retrieve the response from the php file im posting to and then send them to a js function please.
I also have a animated gif image in the script which doesnt show the animation. Can anyone get this working too?
the php response is in this format variable1=blabla&varaibale2=blabla
function sendPixelData(e:MouseEvent):void {
capture_mc.visible = false;
send_mc.visible = false;
txtReturn.htmlText="Uploading Image......<img src="loading.gif" /><br/> Please Wait!";
var output:String = "";
var col = "";
for (var i:Number=0; i<bitmapData.height; i++) {
for (var j:Number=0; j<bitmapData.width; j++) {
col = bitmapData.getPixel(j,i).toString(16);
// In some cases, the color will be truncated (e.g. "00FF00" becomes "FF00")
// so we are adding the missing zeros.
while (col.length<6) {
col = "0" + col;
}
output += col;
}
}
var request:URLRequest = new URLRequest("GetPixelData.php");
var variables:URLVariables = new URLVariables();
var myURLLoader:URLLoader = new URLLoader();
variables.pixels=output;// all image pixel
//trace("output" + output)
variables.width=videoPreviewWidth;// video width
variables.height=videoPreviewHeight;// video height
request.data=variables;
request.method=URLRequestMethod.POST;
myURLLoader.addEventListener ("complete", onC);
myURLLoader.load (request);
function onC (e) {
var result:String =
ExternalInterface.call( "redirectToURL(send variables here)" );
trace ("save complete");
}
}
The result from PHP is stored in the data property of the URLLoader, so to retrieve it use:
function onC (e:Event) {
var result:String = String(e.target.data);
...etc
For part 2 of your question, Flash doesnt support gif file format - you need to use jpg or png.
BTW, dont use strings for event types - use the event type constant, eg:
myURLLoader.addEventListener (Event.COMPLETE, onC);

Save Google charts as a image

So after hours of websearching, googling and overflowing i can't find the solution to my problem.
I got a linechart from Google charts. I want to convert it to PNG, save it on the server en insert it into a MySQL database.
Sounds simple, but i cant get it to work. The script from this website isnt working anymore (atleast not here) http://www.battlehorse.net/page/topics/charts/save_google_charts_as_image.html -> Not working.
Second option is the old option:
$imageData = file_get_contents('http://chart.apis.google.com/chart... etc');
I cant use that because its not supported anymore and cant get some decent quality out of it.
Is there anybody here that can give a good tutorial or help for my problem?
EDIT:
I used the code from Battlehorse combined with the code from EriC.
So now i got this working to show the chart as an image in a DIV i want to save this image on the server and update the mysql to use it in the future to use it in PDF files.
When you visit the site, paste this in the console (overwriting the malfunctioning function).
function getImgData(chartContainer) {
var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
var svg = chartArea.innerHTML;
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('width', chartArea.offsetWidth);
canvas.setAttribute('height', chartArea.offsetHeight);
canvas.setAttribute(
'style',
'position: absolute; ' +
'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
doc.body.appendChild(canvas);
canvg(canvas, svg);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData;
}
In JS it was searching for an iframe bla bla to get the svg.
To automatically save the image, you can just let the method being invoked programmatically.
document.body.addEventListener("load", function() {
saveAsImg( document.getElementById("pie_div")); // or your ID
}, false );
For saving images serverside, this post could be helpful save a PNG image server-side
Update
Posting images to PHP (index.js)
function saveToPHP( imgdata ) {
var script = document.createElement("SCRIPT");
script.setAttribute( 'type', 'text/javascript' );
script.setAttribute( 'src', 'save.php?data=' + imgdata );
document.head.appendChild( script );
}
function save() {
var canvas = document.getElementById("canvas"), // Get your canvas
imgdata = canvas.toDataURL();
saveToPHP( imgdata );
}
function drawOnCanvas() {
var canvas = document.getElementById("canvas"), // Get your canvas
ctx = canvas.getContext("2d");
ctx.strokeStyle = "#000000";
ctx.fillStyle = "#FFFF00";
ctx.beginPath();
ctx.arc(100,99,50,0,Math.PI*2,true);
ctx.closePath();
ctx.stroke();
ctx.fill();
}
drawOnCanvas(); // Test
save();
save.php
<?php
// Get the request
$data = $_GET['data'];
// Save to your DB.
?>
You can use the grChartImg library. It's a cross browser solution and supports even old versions of IE (8 and earlier).It has many features such as download image,upload to the server, show the image in a dialog etc.
For more info look at http://www.chartstoimage.eu.
i hope help you.
This is not really an answer but might be one in the future and it is nescesary if you just want the feature back. The following URL shows all the current issues and feature requests for the visualization API.
https://code.google.com/p/google-visualization-api-issues/issues/list?can=2&q=&sort=-stars+id&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary%20Stars
The more stars/votes this feature request gets, the higher the chance they will take a look at it.
I have the same issue - Save Google charts as image on server. None of answers here works for me. Finally I get solution but with some bugs(working only in Chrome browser). As base I used script from here https://gist.github.com/mpetherb/7085315 I made some changes for my project. I use jquery for importing generated graph image to to my server.
This is a graph that I want to convert to image and save google graph example id="ex0"
Script for converting to image and importing to server
<script>
function getImgData(chartContainer) {
var chartArea = chartContainer.getElementsByTagName('svg')[0].parentNode;
var svg = chartArea.innerHTML;
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('width', chartArea.offsetWidth);
canvas.setAttribute('height', chartArea.offsetHeight);
canvas.setAttribute(
'style',
'position: absolute; ' +
'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
doc.body.appendChild(canvas);
canvg(canvas, svg);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData;
}
function toImg(chartContainer, imgContainer) {
var doc = chartContainer.ownerDocument;
var img = doc.createElement('img');
var myimg=img.src = getImgData(chartContainer);
//Here I am using jquery for importing decoded image to hidden.php on my server
$.ajax({
method: "POST",
url: "hidden.php",
data: { name: myimg } });
while (imgContainer.firstChild) {
imgContainer.removeChild(imgContainer.firstChild);
}
imgContainer.appendChild(img);
}
</script>
<button onclick="toImg(document.getElementById('ex0'), document.getElementById('ex0'));"
type="button" <Convert to image and upload on server></button>
// ex0 - div id of this type of google graph. If you using another type of google graph - you should change it
Don't forget include jquery to your code.
and php hidden script for receiving data from jquery method POST and saving it on server
hidden.php file
<?php
if(isset($_POST['name']))
{
$data = $_POST['name'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
file_put_contents('graph_temp.png', base64_decode($data));
I will notice again - works only in Chrome browser. Firefox also create image file on server but without any content (looks like firefox not support base64 encoded data)

Categories