php How to Open Save As Dialog? Script Downloads Automatically - javascript

I have a download button that fires htmlcanvas and downloads html and saves it as a png file. I did not configure it as I don't understand javascript. I have played around with several tutorials for downloading files but I cannot get a dialog to open on click, regardless of which tutorial I have tried the image downloads to the download folder of whatever device the page is being viewed on. I think this is an issue with the javascript and not the php?
<script type="text/javascript">
var $loading = $('#loader').hide();
$('#carddownload').on('click', function() {
showimage();
});
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
function showimage(){
html2canvas([document.getElementById('card')], {
onrendered: function(canvas)
{
var img = canvas.toDataURL()
$.post("save.php", {data: img}, function (file) {
window.location.href ="downloadpng.php?path="+ file});
}
});
}
</script>
<?php
$file = trim($_GET['path']);
// force user to download the image
if (file_exists($file)) {
header('Content-Type: application/download');
header('Content-Description: File Transfer');
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
unlink($file);
exit;
}
else {
echo "error not found";
}
?>

Related

Why my ajax request always throws error?

Here is my code:
PHP:
public function export(Request $request){
$file = "export.txt";
if(isset($_POST["type"])){
file_put_contents("$file",$_POST["text"]);
}
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: text/plain'); // the appropriate header type for txt file
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
}
JS:
$(document).on('click', '#export', function () {
var names = ['علی','فرید'];
var namess = names.join('\n');
$.ajax({
type: "post",
url: "/export",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
type: "save",
text: namess
},
dataType: "json",
success: function(){
var href = '/export?filename=export.txt';
window.location = href;
},
error: function(){
alert('wrong');
}
});
})
Always error part executes. I mean it always alert wrong. How can I fix it? All I'm trying to do it making a .txt download file.
Noted that when I run this path: http://localhost:8000/export?filename=export.txt .. then export.txt will be downloaded.
You can download using this code:
window.location="export?filename=export.txt";
If you want to post data :
$('<form action="comments.php" method="POST"/>')
.append($('<input type="hidden" name="type" value="save">'))
.append($('<input type="hidden" name="text" value="'+ namess +'">'))
.appendTo($(document.body)) //it has to be added somewhere into the <body>
.submit();
Full code:
$(document).on('click', '#export', function () {
var names = ['علی','فرید'];
var namess = names.join('\n');
$('<form action="export?filename=export.txt" method="POST"/>')
.append($('<input type="hidden" name="type" value="save">'))
.append($('<input type="hidden" name="text" value="'+ namess +'">'))
.appendTo($(document.body)) //it has to be added somewhere into the <body>
.submit();
});
});
Basically Ajax is not usually used for file download however you can tune to make it feel and that is what you have done the only thing is when the request is successful us a "document.location" function from javascript to popup a new window for downloading a file. Besides for the error you are getting, try debugging your PHP code by playing around with your PHP header by starting with most important PHP Headers such as
header('Content-Type: text/plain');
header('Content-Disposition: attachment;filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
ob_clean();
flush();
readfile($fileName);
exit;
check you code works with minimal information if it works then start adding more header one at a time, this helps in resolving problem with minimal information.
Hope this helps.

PHP Screenshot - button

I have a button which saves screenshots, but unfortunately when you click nothing happens
JavaScript
function take_screenshot() {
html2canvas(document.body, {
onrendered: function(canvas) {
var img = canvas.toDataURL()
$.post("save_screenshot.php", {data: img}, function (file) {
window.location.href = "save_screenshot.php?file="+ file
});
}
});
}
PHP
<?php
if($_GET['file']) {
$file=$_GET['file'];
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
unlink($file);
exit;
}
}
if($_POST['data']) {
$data = $_POST['data'];
$file = md5(uniqid()) . '.png';
$uri = substr($data,strpos($data,",")+1);
file_put_contents('./'.$file, base64_decode($uri));
echo $file;
exit();
}
I want to be a screen save as png and me to chose locations. I used the guide on the internet and it seems to me that it should work
You need to split the dataUrl, because it is delimited by ,
function take_screenshot() {
html2canvas(document.body, {
onrendered: function(canvas) {
var img = canvas.toDataURL()
$.post("save_screenshot.php", {data: img.split(',').pop()}, function (file) {
window.location.href = "save_screenshot.php?file="+ file
});
}
});
}

How to download image from php file with javascript

I got the code from this link
but i have a problem with that. I extract the image from php file as under:-
<img src="http://localhost/wordpress/image.php" class="downloadable" id="mainimage"/>
and then i want to download it with javascript as under:-
$('img.downloadable').each(function(){
var $this = $(this);
$this.wrap('<a href="' + $this.attr('src') + '" download />')
});
The problem is that it download php file but i want to download it as PNG.
Extracts of image.php are as under:-
header ("Content-type: image/png");
$userinput = $_GET["user_input"];
$image=imagecreatefrompng('myimages/***image.png***');
$font_file = 'fonts/PR8Charade.ttf';
$col1 = imagecolorallocate($image, 129, 125,11);
$text_size1 = 36;
$xposition1 = 245;
$yposition1 = 380;
$angeldirection1 = 50;
imagettftext($image, $text_size1, $angeldirection1, $xposition1, $yposition1, $col1, $font_file, $userinput);
ImagePng($image);
imagedestroy($image);
I want to download the image.png file from image.php.
<?php
//path to png image
$file = 'picture.png';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}
?>

Download Pdf with php, Not working in explorer and safari

I've got a script to download pdf after submitting a form to db works fine on chrome and firefox but when i download my pdf on safari or explorer my pdf is empty and cannot be opened, i have tried many things, right now im using javascript whit window.location and it works on safari and explorer but i would really like my php script to work on all browsers
<?php
ob_start();
if ($_REQUEST["action"] == "download") {
$file = base64_decode($_REQUEST["download"]);
//Insert to download table....
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$agent = $_SERVER['HTTP_USER_AGENT'];
}
if (strlen(strstr($agent, 'Firefox')) > 0) {
$browser = 'firefox';
} else if (strlen(strstr($agent, 'Chrome')) > 0) {
$browser = 'chrome';
} else {
$browser = 'safari';
}
if ($browser == 'safari'){
?>
<script type="text/javascript">
window.location = '<?php echo $file;?>';
</script>
<?php
} else { ?>
<?php
if ($file) {
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);
header('Content-Type: application/octet-stream');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($file)) . ' GMT');
header('Content-Disposition: attachment; filename='.basename($file));
header("Content-Transfer-Encoding: binary");
header('Content-Length: ' . filesize($file)); // provide file size
header('Connection: close');
readfile($file);
exit();
}
}
}
I solved the problem by removing some of the headers, now im only using this
<?php
ob_start();
if ($_REQUEST["action"] == "download") {
$file = base64_decode($_REQUEST["download"]);
if ($file) {
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header("Content-disposition: attachment; filename=".basename($file));
header("Content-type: application/pdf");
readfile($file);
exit();
}
}
you should use the function ob_flush(); if you want to publish this kind of document in explorer

How to force file download upon jQuery AJAX success?

I'm generating a file dynamically in php like this :
$attachment_url = "http://www.mysite.com/file.jpg";
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.basename( $attachment_url ).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
readfile( $attachment_url );
This data in then passed through jQuery.ajax
I'd like to make it open a file download dialog upon success.
Right now I have this :
success: function(data, textStatus, XMLHttpRequest) {
var win = window.open();
win.document.write(data);
}
This does open a new window and display the raw file data. Instead I would like a download dialog to open.
I'm not sure I have all the necessary information, but you could achieve the goal with 3 files.
download.php
$file = $_GET['file'];
$path = '/var/www/html/';
$attachment_url = $path.$file;
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private',false);
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename="'.basename( $attachment_url ).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: close');
readfile( $attachment_url );
api.php
if (isset($_GET['generate_file'])) {
$str = '';
for($i = 0; $i < 10; $i++) {
$str .= "Number $i\n";
}
$name = 'file.txt';
$path = '/var/www/html/';
file_put_contents($path.$name, $str);
echo $name;
}
ajax.html
<script type="text/javascript">
$.ajax({
url: '/api.php',
data: {
generate_file: true
}
})
.done(function(name) {
$('#results').append('' + name + '');
document.getElementById('link').click(); // $('#link').click() wasn't working for me
$('#link').remove();
});
</script>
<div id="results"></div>

Categories