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();
Related
I am trying to process a form with ajax, jquery and php and I am getting a 404 error, searched before I posted but I did not find the answer to help me fix my problem, this is the .js file :
$(document).ready(function() {
$('form #error-message').hide();
$('#submit').on('click' , function(e) {
e.preventDefault();
var valid = '';
var required = " is required";
var fname = $('form #fname').val();
var lname = $('form #fname').val();
var dbirth = $('form #dbirth').val();
var adress1 = $('form #adress1').val();
if (fname = '' || fname.lenght <= 2) {
valid += '<p><span>X</span> Full Name ' + required + '</p>';
}
if (lname = '' || lname.lenght <= 2) {
valid += '<p><span>X</span> Full Name ' + required + '</p>';
}
if (dbirth = '' || dbirth.lenght <= 2) {
valid += '<p><span>X</span> Full Name ' + required + '</p>';
}
if (adress1 = '' || adress1.lenght <= 5) {
valid += '<p><span>X</span> Full Name ' + required + '</p>';
}
if(valid != '') {
$('form #error-message').removeClass().addClass('warning')
.html('<h1>Please complete all the fields</h1>' + valid);
} else {
var contactData = $( 'form' ).serialize();
console.log(contactData);
$.ajax({
type: 'POST',
url: 'ajaxform/process.php',
data: contactData,
success: function() {
$('#error-message').removeClass().addClass('success')
.html("<h1>Thank you for contacting me. I will reply as soon as i can!</h1>");
},
error: function() {
$('#error-message').removeClass().addClass('alert-error')
.html("An error has occured. Please try again later")
},
complete: function() {
$('form')[0].reset();
}
});
}
});
});
and this is the .php file :
<?php
sleep(1);
$to = 'yourcompany#gmail.com';
$subject = 'My form contact';
if( isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['dbirth']) && isset($_POST['adress1'])) {
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$sdate = trim($_POST['dbirth']);
$adress1 = trim($_POST['adress1']);
if(!empty($fname) && !empty($lname) && !empty($dbirth) && !empty($adress1)) {
$full_name = $fname . " " . $lname;
$body = $full_name . "\n" . $adress1;
$headers = "From {$full_name} " . $dbirth;
mail($to, $subject, $body, $headers);
}
} else {
header('location: ../index.html');
}
?>
I suggest you phpmailer. You can download it at this link.
<?php
require_once('class.phpmailer.php');
sleep(1);
$to = 'yourcompany#gmail.com';
$subject = 'My form contact';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 1; // will send erros and messages
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'tls';
$mail->Host = "smtp.gmail.com";
$mail->Port = 587; //Gmail smtp port
$mail->Username = "youremail#gmail.com";
$mail->Password = "yourpassword";
$mail->SetFrom($headers);
$mail->Subject = $subject;
if( isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['dbirth']) && isset($_POST['adress1'])) {
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);
$sdate = trim($_POST['dbirth']);
$adress1 = trim($_POST['adress1']);
if(!empty($fname) && !empty($lname) && !empty($dbirth) && !empty($adress1)) {
$full_name = $fname . " " . $lname;
$body = $full_name . "\n" . $adress1;
$headers = "From {$full_name} " . $dbirth;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
header('location: ../index.html');
}
}
}
?>
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.
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.
I am working on a admin panel which is going to add data on a SQLite DB using AngularJS and PHP and then show it in HTML. All good with data as arrays text date etc. The problem that I have is to upload an Image in a specified folder and store the path in my DB.
This is my PHP which store data in DB
<?php
try {
if (
empty($_POST['item']) ||
empty($_POST['description']) ||
empty($_POST['release']) ||
empty($_POST['demo']) ||
empty($_POST['type']) ||
empty($_POST['live']) ||
empty($_POST['client'])
) {
throw new PDOException("Invalid Request");
}
$item = $_POST['item'];
$description = $_POST['description'];
$release = $_POST['release'];
$demo = $_POST['demo'];
$type = $_POST['type'];
$live = $_POST['live'];
$client = $_POST['client'];
$objDb = new PDO('sqlite:../database/database');
$objDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO 'items'
('id', 'item', 'description', 'release', 'demo', 'type', 'live', 'client')
VALUES (null, ?, ?, ?, ?, ?, ?, ?)";
$statement = $objDb->prepare($sql);
if (!$statement->execute(array($item, $description, $release, $demo, $type, $live, $client))) {
throw new PDOException("The execute method failed");
}
And this is my PHP which upload Images in a specified folder
<?php
if (isset($_POST['submit'])) {
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 1000000)
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
echo "<span>Your File Uploaded Succesfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <b>already exists.</b> ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "<b>Stored in:</b> " . "upload/" . $_FILES["file"]["name"];
}
}
} else {
echo "<span>***Invalid file Size or Type***<span>";
}
}
?>
And this is my insert function from angular
$scope.insert = function() {
if ($scope.goodToGo()) {
var thisData = "item=" + $scope.item;
thisData += "&description=" + $scope.description;
thisData += "&release=" + $scope.release;
thisData += "&demo=" + $scope.demo;
thisData += "&client=" + $scope.client;
thisData += "&type=" + $scope.type;
thisData += "&live=" + $scope.live;
thisData += "&image=" + $scope.image;
$http({
method : 'POST',
url : urlInsert,
data : thisData,
headers : {'Content-Type' : 'application/x-www-form-urlencoded'}
})
.success(function(data){
if(_recordAddedSuccessfully(data)){
$scope.items.push({
id : data.item.id,
item : data.item.item,
description : data.item.description,
release : data.item.release,
demo : data.item.demo,
client : data.item.client,
client_name : data.item.client_name,
type : data.item.type,
type_name : data.item.type_name,
live : data.item.live,
live_name : data.item.live_name,
image : data.item.image,
done : data.item.done
});
$scope.clear();
}
})
.error(function(data, status, headers, config){
throw new Error('Something went wrong with inserting');
});
}
};
Have anyone any idea how to do this?
If you are uploading image then content type should be set to multipart/form-data i.e
headers : {'Content-Type' : 'multipart/form-data'}
rest looks fine.
As a js-firsttimer, wanna ask if script below is proper (security), considering that filetype is detected and processed via php.
http://jsfiddle.net/kwCks/2/
var _URL = window.URL || window.webkitURL;
$("#file").change(function(e) {
var file, img, size;
if ((file = this.files[0])) {
if(file.size < "5100000"){
size = "good";
img = new Image();
img.onload = function() {
if((this.height/(this.width / 64)) < "200"){
if(size == "good"){
//alert("ok to upload");
$("#blah").attr("src", img.src);
}
}else{ alert("File is too big (dimensions)");}
};
img.src = _URL.createObjectURL(file);
} else {
size = "big";
alert("File is too big, use 5MB or smaller");
}
}
});
EDIT PHP PART
if(isset($_POST["titletext"])){
echo $_POST["titletext"];
if (!$_FILES["avafile"]["error"] > 0) {
echo "Upload: " . $_FILES["avafile"]["name"] . "<br>";
echo "Type: " . $_FILES["avafile"]["type"] . "<br>";
echo "Size: " . ($_FILES["avafile"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["avafile"]["tmp_name"] . "<br>";
move_uploaded_file($_FILES["avafile"]["tmp_name"], "upload/" . md5($_FILES["avafile"]["name"]));
echo '<img class="img-rounded" style="width: 64px;" src="./upload/'.$_FILES["avafile"]["name"].'">';
}
}
Also wanna now if there's a way to detect script/text uploaded as image and use some "striptags" for it.
Images are being uploaded with md5(something) name.