Download Google Drive file using javascript - javascript

I want to download Google Drive file using javascript to my server when i click on Google Drive picker but cannot get the file downloaded. I have been searching if for 4 days but the issue is same below is the code that i am using.
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
var id = data.docs[0].id;
var request = new XMLHttpRequest();
request.open('GET', 'https://www.googleapis.com/drive/v2/files/' + id);
request.setRequestHeader('Authorization', 'Bearer ' + gapi.auth.getToken().access_token);
request.addEventListener('load', function() {
var item = JSON.parse(request.responseText);
console.log(item);
downloadFile(item);
});
request.send();
}
}
function downloadFile(item) {
var request = new XMLHttpRequest();
var mimeType = item['mimeType'];
if (typeof item.exportLinks != 'undefined') {
if (mimeType == 'application/vnd.google-apps.spreadsheet') {
mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
}
url = item['exportLinks'][mimeType];
link = url;
} else {
lien = item['downloadUrl'].split("&");
link = lien[0] + '&' + lien[1];
url = item['downloadUrl'];
}
title = item['title'];
type = mimeType;
filesize = item['fileSize'];
fileext = item['fileExtension'];
id = item['id'];
var datatable = $.param({ url: url, title: title, type: type, filesize: filesize, fileext: fileext, id: id});
request.open("POST", "ajax-db-files/copy_drive_file.php?" + datatable, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send("datatable=" + datatable);
}
and the php file is:
$upload_path='sss';
if (isset($_POST['exportFormat'])) {
$pieces = explode(",", $_POST['exportFormat']);
$url = $_POST['datatable'] . '&exportFormat=xlsx';
$title = $pieces[1];
$type = $pieces[2];
$fileext = $pieces[0];
$fileId = $pieces[5];
}else {
$url = $_POST['datatable'] . '&e=download';
$pieces = explode(",", $_POST['gd']);
$onlytitle = explode(".", $pieces[1]);
$title = $onlytitle[0];
$type = $pieces[2];
$filesize = $pieces[3];
$fileext = $pieces[4];
$fileId = $pieces[5];
}
$fullPath = $upload_path.'/'.$title.'.'. $fileext;
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
//header("Content-type: " . $type . "");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$title.'.'.$fileext."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $filesize);
// folder to save downloaded files to. must end with slash
$destination_folder = $upload_path.'/';
$newfname = $destination_folder . basename($title . '.' . $fileext);
$file = fopen($url, "rb");
if ($file) {
$newf = fopen($newfname, "wb");
if ($newf)
while (!feof($file)) {
fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
ob_end_flush();

TLDR;
You need to serialize datatable into a URL-encoded string first.
Explanation
var datatable = [url, title, type, filesize, fileext,id];
Here, you're creating datatable as an array
request.open("POST", "ajax-db-files/copy_drive_file.php?" + datatable, true);
request.send("datatable=" + datatable);
Then, in these two lines, you try to concatenate the array directly to the string, which casts the array to a string by calling .join(',') on the array.
What you need is to serialize the array into URL-encoded notation. If you're using jQuery, try var datatable = $.param({ url: url, title: title, type: type, filesize: filesize, fileext: fileext, id: id]); instead.

Related

JQuery Autocomplete's source from db using json

I'm trying to make jquery autocomplete input field with source from database, and the data is stored in json. I stored all data I got in one variable, it's look like this :
and when I set source to be value of that sinput field, I got the whole sentece (which is expect from my example)..but now I know to have three words (first - skijanje, second - vodopoad, third - more) so to have three options in my autocomplete. Here is my code for getting data using php:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "user_name", "user_pass", "db_name");
$result = $conn->query("SELECT `title`, `type` FROM " . $obj->table);
$output = array();
$output = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($output);
Here is js code for reading that data :
<script>
var obj, dbParam, xmlhttp,x , txt = "";
var i = 0;
obj = { "table":"tourplan" };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = "All data: " + this.responseText;
var myObj = JSON.parse(this.responseText);
for (x in myObj) {
txt += myObj[x].title +" ";
}
document.getElementById("demo2").value = txt;
//document.getElementById("demo2").innerHTML = "Only one field: " + myObj[1].title;
}
}
xmlhttp.open("GET", "tourTitle.php?x=" + dbParam, true);
xmlhttp.send();
</script>
<p id="demo"></p>
<input type="text" id="demo2" value="">
for document.getElementByID('demo').innerHTML = "All data: " + this.responseText; I got this:
All data: [{"title":"skijanje","type":"zima"},{"title":"vodopad","type":"jesen - proljece - ljeto"},{"title":"more","type":"ljeto"}]
and here is for making autocomplete:
<script>
$( function() {
var otherPlaces = [
txt
];
$("#search-loged").autocomplete({
source: txt
});
});
</script>
ANy idea for correct that? thanks
Don't use pure ajax, try something like this:
jQuery Ajax
$( function() {
$("#search-loged").autocomplete({
source: 'tourTitle.php',
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
});
HTML
<p id="demo"></p>
<input type="text" id="demo2" value="" name='x'>
PHP
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "user_name", "user_pass", "db_name");
$result = $conn->query("SELECT `title`, `type` FROM " . $obj->table);
$output = array();
$output = $result->fetch_all(MYSQLI_ASSOC);
$response = array();
foreach($output as row){
$response[] = ["value"=>$row['title'],"label"=>$row['title']];
}
echo json_encode($response);

Converting canvas to PDF crashes browser

I am using Fabric.js for working on a canvas. Once complete, I scale it up to the size required for upload since the workspace for the canvas has to fit on a screen and my actual uploaded file needs to be approx. 14,000 px in width and 8,750 px in height. If I create an image, it creates it in a few seconds without issue. When I try to create a PDF using jsPDF, it crashes.
This works for creating the image from a Fabric.js canvas:
var dataURL = canvas.toDataURL({
format: 'png',
multiplier: 20
})
document.write('<img src="' + dataURL + '"/>');
And this fails to create the PDF/crashes the browser:
var dataURL = canvas.toDataURL({
format: 'png',
multiplier: 20
})
var pdf = new jsPDF();
pdf.addImage(dataURL, 'PNG', 0, 0);
pdf.save("download.pdf");
}
Given your image dimensions, this is simply a too big task to be done on the client side.
As the above solution tried to point out, you need to to this on the server side, regardless of the technology you are using.
JQuery Code:
First you get active object of canvas the go throw
dataArray.push({
"objFlipX" : obj_Tshirt_canv.item(i).getFlipX(),
"objFlipY" : obj_Tshirt_canv.item(i).getFlipY(),
"objWidth" : obj_Tshirt_canv.item(i).getWidth(),
"bojHeight" : obj_Tshirt_canv.item(i).getHeight(),
"objOriginX" : obj_Tshirt_canv.item(i).getLeft(),
"objOriginY" : obj_Tshirt_canv.item(i).getTop(),
"objImgSrc" : obj_Tshirt_canv.item(i).getSrc(),
"objAngel" : obj_Tshirt_canv.item(i).getAngle(),
"objScalex" : obj_Tshirt_canv.item(i).getScaleX(),
"objScaley" : obj_Tshirt_canv.item(i).getScaleY(),
"objType" : 'image'
});
$.ajax({
url : " ",
type : "POST",
data : {
dataArray : dataArray
},
cache : false,
success : function(data) {
alert("data update successfully");
hideLoder();
},
error : function(xhr, status, error) {
alert("Not Successfull");
}
});
Now crate php file and create object of fpdf like
require ('fpdf.php');
$aaa = $_REQUEST['action'];
$aaa();
function createpdf() {
$size = Array(840, 990);
$data = $_REQUEST['dataArray'];
$width = 280;
$height = 330;
$_actualratioWid = 840 / $width;
$_actualratioHig = 990 / $height;
$fpdfObj = new FPDF("p", "pt", $size);
$fpdfObj -> AddPage();
foreach ($data as $key => $value) {
$x = $value[objOriginX] * $_actualratioWid;
$y = $value[objOriginY] * $_actualratioHig;
$height = $value[bojHeight] * $_actualratioHig;
$width = $value[objWidth] * $_actualratioHig;
$_flipx = ($value[objFlipX]);
$_flipy = ($value[objFlipY]);
$imgsrc = $value[objImgSrc];
$dataTppe = $value[objType];
$rotation = $value[objAngel];
$color=$value[objcol];
$randomString = MyStringr();
$_filename1 = $_SERVER["DOCUMENT_ROOT"] . "path" . $randomString . ".png";
if ($value[objType] === 'text' && $value[objval] != " ") {//new code to be imp
$image_src = $_SERVER["DOCUMENT_ROOT"] . " path". $randomString . ".png";
exec('convert -background transparent -depth 8 -size 500 -fill "' . $color .'" -pointsize 70 label:"' . $value[objval] .'" "'. $image_src.'"');
$fpdfObj -> Image($image_src, $x, $y);
} else {// work done
$imgsrc = str_replace(" path", $_SERVER["DOCUMENT_ROOT"], $imgsrc);
if ($_flipx == "false" && $_flipy == "false") {
$fpdfObj -> Image($imgsrc, $x, $y, $height, $width);
} else if ($_flipy == "true" && $_flipx == "false") {
exec(' convert "' . $value[objImgSrc] . '" -flip ' . $_filename1);
$fpdfObj -> Image($_filename1, $x, $y, $height, $width);
}
else if($_flipx== "true" && $_flipy=="false")
{ exec(' convert "' . $value[objImgSrc] . '" -flop ' . $_filename1);
$fpdfObj -> Image($_filename1, $x, $y, $height, $width);
}
}//end else
}//foreach
while (true)//generate random file name when cart is added by user in tool
{
$filename = uniqid('AddCart', true) . '.pdf';`enter code here`
if (!file_exists(sys_get_temp_dir() . $filename))
break;
}
$fpdfObj -> Output($_SERVER["DOCUMENT_ROOT"] . "path " . $filename);
}//end createpdf ()
function MyStringr()//return random file name
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}

Download file to server directly from Google Drive in php

I want to transfer file from Google Drive to my Server Directly when any user selects a file from Google Drive Picker. I am using following code but the file does not get downloaded in my particular folder when using following code..
Callback Function:
function onPickerAction(data) {
if (data.action === google.picker.Action.PICKED) {
var id = data.docs[0].id;
var request = new XMLHttpRequest();
request.open('GET', 'https://www.googleapis.com/drive/v2/files/' + id);
request.setRequestHeader('Authorization', 'Bearer ' + gapi.auth.getToken().access_token);
request.addEventListener('load', function() {
var item = JSON.parse(request.responseText);
console.log(item);
downloadFile(item);
});
request.send();
}
}
Function to download File:
function downloadFile(item) {
var request = new XMLHttpRequest();
var mimeType = item['mimeType'];
if (typeof item.exportLinks != 'undefined') {
if (mimeType == 'application/vnd.google-apps.spreadsheet') {
mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
}
url = item['exportLinks'][mimeType];
link = url;
} else {
lien = item['downloadUrl'].split("&");
link = lien[0] + '&' + lien[1];
url = item['downloadUrl'];
}
title = item['title'];
type = mimeType;
filesize = item['fileSize'];
fileext = item['fileExtension'];
id = item['id'];
var datatable = [url, title, type, filesize, fileext,id];
document.getElementById("myddlink").href=link;
request.open("POST", "downloadfile.php?" + datatable, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send("datatable=" + datatable);
}
Php File:
$upload_path='upload_folder';
if (isset($_POST['exportFormat'])) {
$pieces = explode(",", $_POST['exportFormat']);
$url = $_POST['datatable'] . '&exportFormat=xlsx';
$title = $pieces[1];
$type = $pieces[2];
$fileext = $pieces[0];
$fileId = $pieces[5];
}else {
$url = $_POST['datatable'] . '&e=download';
$pieces = explode(",", $_POST['gd']);
$onlytitle = explode(".", $pieces[1]);
$title = $onlytitle[0];
$type = $pieces[2];
$filesize = $pieces[3];
$fileext = $pieces[4];
$fileId = $pieces[5];
}
$fullPath = $upload_path . '/' . $title . '.' . $fileext;
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: " . $type . "");
header("Content-Disposition: attachment; filename=\"" . $title . '.' . $fileext . "\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $filesize);
// folder to save downloaded files to. must end with slash
$destination_folder = $upload_path . '/';
$newfname = $destination_folder . basename($title . '.' . $fileext);
$file = fopen($url, "rb");
if ($file) {
$newf = fopen($newfname, "wb");
if ($newf)
while (!feof($file)) {
fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
ob_end_flush();

File Not Downloaded in Correct format on Server from google drive using php [duplicate]

I want to download Google Drive file using javascript to my server when i click on Google Drive picker but cannot get the file downloaded. I have been searching if for 4 days but the issue is same below is the code that i am using.
function pickerCallback(data) {
if (data.action == google.picker.Action.PICKED) {
var id = data.docs[0].id;
var request = new XMLHttpRequest();
request.open('GET', 'https://www.googleapis.com/drive/v2/files/' + id);
request.setRequestHeader('Authorization', 'Bearer ' + gapi.auth.getToken().access_token);
request.addEventListener('load', function() {
var item = JSON.parse(request.responseText);
console.log(item);
downloadFile(item);
});
request.send();
}
}
function downloadFile(item) {
var request = new XMLHttpRequest();
var mimeType = item['mimeType'];
if (typeof item.exportLinks != 'undefined') {
if (mimeType == 'application/vnd.google-apps.spreadsheet') {
mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
}
url = item['exportLinks'][mimeType];
link = url;
} else {
lien = item['downloadUrl'].split("&");
link = lien[0] + '&' + lien[1];
url = item['downloadUrl'];
}
title = item['title'];
type = mimeType;
filesize = item['fileSize'];
fileext = item['fileExtension'];
id = item['id'];
var datatable = $.param({ url: url, title: title, type: type, filesize: filesize, fileext: fileext, id: id});
request.open("POST", "ajax-db-files/copy_drive_file.php?" + datatable, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send("datatable=" + datatable);
}
and the php file is:
$upload_path='sss';
if (isset($_POST['exportFormat'])) {
$pieces = explode(",", $_POST['exportFormat']);
$url = $_POST['datatable'] . '&exportFormat=xlsx';
$title = $pieces[1];
$type = $pieces[2];
$fileext = $pieces[0];
$fileId = $pieces[5];
}else {
$url = $_POST['datatable'] . '&e=download';
$pieces = explode(",", $_POST['gd']);
$onlytitle = explode(".", $pieces[1]);
$title = $onlytitle[0];
$type = $pieces[2];
$filesize = $pieces[3];
$fileext = $pieces[4];
$fileId = $pieces[5];
}
$fullPath = $upload_path.'/'.$title.'.'. $fileext;
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
//header("Content-type: " . $type . "");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$title.'.'.$fileext."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . $filesize);
// folder to save downloaded files to. must end with slash
$destination_folder = $upload_path.'/';
$newfname = $destination_folder . basename($title . '.' . $fileext);
$file = fopen($url, "rb");
if ($file) {
$newf = fopen($newfname, "wb");
if ($newf)
while (!feof($file)) {
fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
ob_end_flush();
TLDR;
You need to serialize datatable into a URL-encoded string first.
Explanation
var datatable = [url, title, type, filesize, fileext,id];
Here, you're creating datatable as an array
request.open("POST", "ajax-db-files/copy_drive_file.php?" + datatable, true);
request.send("datatable=" + datatable);
Then, in these two lines, you try to concatenate the array directly to the string, which casts the array to a string by calling .join(',') on the array.
What you need is to serialize the array into URL-encoded notation. If you're using jQuery, try var datatable = $.param({ url: url, title: title, type: type, filesize: filesize, fileext: fileext, id: id]); instead.

CURL Delete request to Instagram API fails

I'm trying to unlike a photo that I just liked on Instagram with a call to the API. My url is exactly as the URL in instagrams API tool. Im using Curl. I get an empty response, no error or status code.
Here is my "like/unlike" method written in javascript.
likeImage: function(type, id)
{
var params = "url=https://api.instagram.com/v1/media/" + id + "/likes";
if(type === 'DELETE')
{
params += "?access_token=" + localStorage.getItem('id') + "." + localStorage.getItem('token');
}
else
{
params += "&access_token=" + localStorage.getItem('id') + "." + localStorage.getItem('token');
}
$.ajax({
url: "crossDomain.php",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
type: type,
data: params,
beforeSend: function ()
{
console.log('Start' + type);
},
complete: function(data)
{
console.log('Finished ' + type);
},
success: function(data)
{
console.log('Success ' + type);
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('JQXHR:' + jqXHR);
console.log('TEXTSTATUS: ' + textStatus);
console.log('ERROR THROWN:' + errorThrown);
console.log('error');
}
});
And here is my Server Code written in PHP
$method = $_SERVER['REQUEST_METHOD'];
if($method == "POST")
{
$url = $_POST['url'];
$token = $_POST['access_token'];
$fields = array(
"access_token" => urlencode($token)
);
$fields_string = "";
foreach($fields as $key=>$value)
{
$fields_string .= $key.'='.$value.'&';
}
rtrim($fields_string, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
echo $result;
}
else if($method == 'DELETE')
{
$url = file_get_contents('php://input');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
$result = curl_exec($ch);
curl_close($ch);
echo $result;
}
My Like code works Perfectly... any thoughts?
According to the documentation a DELETE request should look like this:
curl -X DELETE https://api.instagram.com/v1/media/{media-id}/likes?access_token=MYACCESSTOKEN
Problem solved. In my PHP delete method, $url started with url=... I just had to remove that.

Categories