I'm creating image using canvas and using following script,
function getImage() {
var canvas1 = document.getElementById("images");
if (canvas1.getContext) {
var ctx = canvas1.getContext("2d");
var myImage = canvas1.toDataURL("image/jpg");
}
$('<form action="download.php" method="POST">' +
'<input type="hidden" name="aid" value="' + myImage + '">' +
'</form>').submit();
}
And in my Download.php file is,
<?php $img = $_POST['aid'];
echo "<img src=".$img.">";
?>
it showing image correctly. But i wanna give download button with jpg format or pdf format.
How i can use?
I used base64_decode(); method. But i cant solve.
Help me...
Thanks for all. but I got answer using,
file_put_contents();
But thing, i dont know how to use. Finally i got it from this Answer.
Answer is,
$data = 'data:image/png;base64,AAAFBfj42Pj4';
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents('/tmp/image.png', $data);
But still i'm waiting for download button with option of image/pdf format.
Try this:
PHP echo'ed image with link
<?php
$img = $_POST['aid'];
echo "";
?>
download_image.php
<?php
$img = "myimage.jpg";
// fix for IE catching or PHP bug issue
header("Pragma: public");
header("Expires: 0"); // set expiration time
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
// browser must download file from server instead of cache
// force download dialog
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// use the Content-Disposition header to supply a recommended filename and
// force the browser to display the save dialog.
header("Content-Disposition: attachment; filename=".basename($img).";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($img));
readfile("$img");
exit();
?>
Related
I have a script that outputs an image.
Works fine
include('../myfolder/myImageScript.php'); // outputs image on page
Fails
echo file_get_contents('../myfolder/myImageScript.php'); // nothing displayed
I think this fails because in php a script, in my case myImageScript.php, isn't executed when called via the file_get_contents() function, but is when called using a include() the script is executed.
I am struggling to get a zip function to work due to the empty output of file_get_contents().
the file i'm trying to call via file_get_contents() is:
myImageScript.php
$imgstr = "data:image/jpeg;base64,/9j/........... rest of string";
if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
die("error");
}
// Decode the data
$content = base64_decode($matches[2]);
// Output the correct HTTP headers
header('Content-Type: '.$matches[1]);
//header("Content-Type: image/jpeg"); // tried this made no difference
// Output the actual image data
echo $content;
Any help would be greatly appreciated.
Something like this should work, BUT you need to enable ZipArchive http://php.net/manual/en/class.ziparchive.php (should not be a problem)
<?php
$imgstr = "data:image/gif;base64,R0lGODlhyAAiALMAAFONvX2pzbPN4p6/2tTi7mibxYiw0d/q86nG3r7U5l2UwZO31unx98nb6nOiyf///yH5BAUUAA8ALAAAAADIACIAAAT/8MlJq7046827/2AojmRpnmiqriwGvG/Qjklg28es73wHxz0P4gcgBI9IHVGWzAx/xqZ0KlpSLU9Y9MrtVqzeBwFBJjPCaC44zW4HD4TzZI0h2OUjON7EsMd1fXcrfnsfgYUSeoYLPwoLZ3QTDAgORAoGWxQHNzYSBAY/BQ0XNZw5mgMBRACOpxSpnLE3qKqWC64hk5WNmBebnA8MjC8KFAygMAUCErA2CZoKq6wHkQ8C0dIxhQRED8OrC1hEmQ+12QADFebnABTr0ukh1+wB20QMu0ASCdn16wgTDmCTNlDfhG/sFODi9iMLvAoOi6hj92LZhHfZ3FEEYNEDwnMK/ykwhDEATAN2C/5d3PiDiYSIrALkg6EAz0hiFDNFJKeqgIEyM1nhwShNo0+glhBhgKlA5qqaE25KY1KAYkGAYlYVSEAgQdU1DFbFe3DgKwysWcHZ+QjAAIWdFQaMgkjk2b4ySLtNkCvuh90NYYmMLUsErVRiC8o8OLmkAYF5hZkRKYCHgVmDAiJJLeZpVUdrq/DA7XB5rAV+gkn/MJ0hc8sKm6OuclDoo8tgBQFgffd335p3cykEjSK1gIXLEl+Oq9OgTIKZtymg/hHuAoHmZJ6/5gDcwvDOyysEDS7B9VkJoSsEhuEyN6KSPyxKrf4qsnIoFQ4syL0qum8i9AW0H/9F/l3gngXwwSAfEQ5csIoFUmH1oAVrTEhXQ+Cdd6GGD4z230b+TQdDgB8S6INeG76AlVSsoYeibBg+cOAX2z1g4Vv2sYggER15uFliZFwWnUAAQmhLGUKe+MMFEa1oH40/FMKYht1RMKVB7+AiwTvEMehdeB2CicwLlAlXI1m5kSjBmACUOQF0HWRpAZcZqngBbxWwqZtkZz4QlEsJvkDiejDIcRh5h4kG5pPBrEHkDw06GKMEhAJwGxx+uBIoAIOmlxaH9TWCh4h2fgqDAWcc019AqwTHwDtu1UmMRQnkdpuHRU6gZ3uWOOaHILmuScc6LlFDhKuwwgiqsjQNgAD/UWgFZaKuq/w0AHIAuHIYReR5+A4C12HkEksSfRvuqiuxR4GebSFw7SraMqoRuXvK2t+Z+JDb22bsxDqBh+YRVCO5RgT81JnEGiNtNvvKKwl/IzJKql8ORadqQuSZis7CANCWYnIScOyAiJHayFIUIpM8r0GUstsrbA4HhC2nJi9LwDuihKkuhEQpgAAiEQpjyc99aWHMppz2gSLBlCL9iFQrW2pdz0TDPCkGCRgQjU9GVPpZQAkgIICWHfQhABkNkM1svQxg9wcJfWSn1AlxI5DA3COYjbbaLJBKzhQRuiF4Cn8nMiMXgQ+uOAkBFDDA2wxABkPJiMe8+OUaECVNLMZUJI755xtoHmwXnoNuugUQp4bGLzf0dvrriy2wsAMD4A377YJjSgDfD0QAADs=";
if (!preg_match('/data:([^;]*);base64,(.*)/', $imgstr, $matches)) {
die("error");
$content = base64_decode($matches[2]);
$zip = new ZipArchive;
$filename = tempnam("/tmp", "testmeZip");
$res = $zip->open($filename, ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.gif', $content);//you can use $matches to figure out extension
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
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: application/octet-stream");
header("Content-Disposition: attachment; filename=\"test.zip\"");
header("Content-Transfer-Encoding: binary");
// make sure the file size isn't cached
clearstatcache();
header("Content-Length: ".filesize($filename));
// output the file
readfile($filename);
I have problem in download image from url,
$url = 'http://example.com/image.php';
$img = '/my/folder/flower.gif';
file_put_contents($img, file_get_contents($url));
in this code file is saving in my server folder .but i needed without saving in my server it needs to be download to user.
set the correct header and echo it out instead of file_put_contents
$url = 'http://example.com/image.php';
header('Content-Disposition: attachment; filename:image.jpg');
echo file_get_contents($url);
Use application/octet-stream instead of image/jpg:
If [the Content-Disposition] header is used in a response with the application/octet-stream content-type, the implied suggestion is that the user agent should not display the response, but directly enter a `save response as...' dialog.
— RFC 2616 – 19.5.1 Content-Disposition
EDIT
function forceDownloadQR($url, $width = 150, $height = 150) {
$url = urlencode($url);
$image = 'http://chart.apis.google.com/chart?chs='.$width.'x'.$height.'&cht=qr&chl='.$url;
$file = file_get_contents($image);
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=qrcode.png");
header("Cache-Control: public");
header("Content-length: " . strlen($file)); // tells file size
header("Pragma: no-cache");
echo $file;
die;
}
forceDownloadQR('http://google.com');
if you want to download the file onto your webserver(and save it), just use copy()
copy($url, 'myfile.png');
I have a PHP script that is working fine for displaying all my images in a directy that I upload to. I wand to make a little download button so someone can click the button and download the image. I am making this for my company so people can download our logos.
<?php
// Find all files in that folder
$files = glob('grips/*');
// Do a natural case insensitive sort, usually 1.jpg and 10.jpg would come next to each other with a regular sort
natcasesort($files);
// Display images
foreach($files as $file) {
echo '<img src="' . $file . '" />';
}
?>
I figue I could just make a button and call the href of $file but that would just link to the file and show the image. I am not sure to have it auto download. Any help would be great.
Just add some headers in a download.php file so you can then read the file in like this:
Make sure you sanitize your data coming to the file, you don't want people to be able to download your php files.
<?php
// Find all files in that folder
$files = glob('grips/*');
// Do a natural case insensitive sort, usually 1.jpg and 10.jpg would come next to each other with a regular sort
natcasesort($files);
// Display images
foreach($files as $file) {
echo '<img src="' . $file . '" /><br />Download Image';
}
?>
download.php
$filename = base64_decode($_GET["file"]);
// Data sanitization goes here
if(!getimagesize($filename) || !is_file($filename)){
// Not an image, or file doesn't exist. Redirect user
header("Location: /back_to_images.php");
exit;
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=".basename($filename).";");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile($filename);
i want to create a downloadscript which allows Force Download of JPGs.
This is my php script:
<?php
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: image/jpg");
header('Content-Disposition: attachment; filename="'.basename($GET['a']).'"');
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize(($GET['a']));
readfile(($GET['a']);
?>
This is a code segment of my js code:
function downloadFile(a){
document.location = "download.php?a="+ a;
}
With this code sample nothing happens. If i append the result into a HTML-tag, it shows the content of the file.
Any ideas how to teach the browser to download this file?
EDIT: SCRIPT UPDATE
You can't download files with ajax. So, if you have something that should happen on ajax, you should return url in response and apply it like document.location = "url"to start download process.
One note here. As I remember, browser will block file download if it is initiated not by user click. So, this will work fine:
.click(function(){
document.location = "download url"
})
But if it is started not by user click, it will be blocked. So, code like this:
.click(function(){
$.ajax({...,
success:function(download_url_from_server){
document.location = download_url_from_server;
}});
})
will be blocked by browser. So, if you want to pass some data with a post, you may submit a form into hidden iframe or to blank page using <form target="...":
function checkToken(token){
var $form = $("#downloadForm");
if ($form.length == 0) {
$form = $("<form>").attr({ "target": "_blank", "id": "downloadForm", "method": "POST", "action": "script.php" }).hide();
$("body").append($form);
}
$form.find("input").remove();
var args = { a: "checkToken", b: token }
for (var field in args) {
$form.append($("<input>").attr({"value":args[field], "name":field}));
}
$form.submit();
}
And in script.php you need to execute code from download.php immediately, if token is Ok, or do a redirect to download script:
header("Location: download.php?a=" . $filename)
Setting the mime type to image/jpeg will most probably not work. So, you need application/octet-stream instead to force the download.
Replace the content type header in your php with the following:
header('Content-Type: application/octet-stream');
Also, One nice solution instead of using document.location is to inject an iframe. Use the following function in your success callback
function downloadFile(url)
{
var iframe;
iframe = document.getElementById("download-container");
if (iframe === null)
{
iframe = document.createElement('iframe');
iframe.id = "download-container";
iframe.style.visibility = 'hidden';
document.body.appendChild(iframe);
}
iframe.src = url;
}
It seems you have errors in your script.
First of all, correct speliing for GET variable is $_GET['a'], not $GET['a'].
The second issue here is that you have extra opening parenthesis, when I copied your code, I received 500 Internal Server Error response.
If we correct mistakes, it seems to work fine.
Just try corrected version of your code.
<?php
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Description: File Transfer");
header("Content-Type: image/jpg");
header('Content-Disposition: attachment; filename="'.basename($_GET['a']).'"');
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($_GET['a']));
readfile($_GET['a']);
?>
You're getting it confused a bit. As FAngel pointed out, you can't download files via AJAX. What you need to do is redirect the user to another page that then has your above PHP code in it. That PHP code should then allow the user to download the file directly. What you're attempting is absolutely possible, you just need to approach it from another direction, ie not with AJAX.
You can force download file with Mouse middle event:
const url = "https://www.google.com.vn/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png";
const forceDownload = url => {
try {
const link = document.createElement('a');
const fileName = url.substring(url.lastIndexOf('/') + 1, url.length);
const event = new MouseEvent( "click", { "button": 1, "which": 1 });
link.href = url;
link.download = fileName;
link.dispatchEvent(event);
} catch(e) {
document.location = url;
}
}
forceDownload(url);
So I am having this problem wit my download link. Basically my previous way of creating download link is to just have a form button with method='link' and the action to be the link to the file. This works for firefox and others but not safari. For some reason, when the user tries to download the file (excel file) from safari, it would just show bunch of ascii characters on the browser (I guess its trying to read it using the browser?). Well, I was looking for another solution and it seems like using header is the way to do it. So now I am tryng to create a form button with method='post' and action='download.php' where there is a hidden field with the link to the file. It looks like this
function showDownloadWithHeader($link){
echo "<form action='download.php' method='post' >";
echo "<input class='downloadButton' type='submit' value='Download Report'>";
echo "<input type='hidden' name='filename' value='$link'>";
echo "</form>";
}
And inside the download.php I would just want the user to be asked to download the file.
<?php
if($_POST['filename'] == '' || empty($_POST['filename'])){
exit;
}
$filename = $_POST['filename']; //the file is 2 folder down. e.g. data/stack/bla.xlsx
$file = $filename;
$extension = end(explode('.', $filename));
error_reporting(E_ALL);
ini_set("display_errors",1);
// echo $filename;
// echo "<br/>";
// echo $extension;
// echo filesize($filename);
// echo "<br/>";
switch($extension){
case 'xls':
$mimeType = 'application/vnd.ms-excel';
break;
case 'xlsx':
$mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
break;
}
// echo $mimeType;
header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
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($filename);
exit;
?>
I saw this solution on php.net under readfile() function but it doesnt seem to be working for me. I am doing this on localhost.
Something like this works fine.
header("Pragma: public", true);
header("Expires: 0"); // set expiration time
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment; filename=".basename($file));
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($file));
die(file_get_contents($file));
If I understand you correctly the script is working as expected, i.e if a browser recognizes mime type:
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
Then it SHOWS it in browser (whether or not it displays correctly is something else)
Since you want to FORCE it to download INSTEAD OF showing in browser use the mime type:
'application/octet-stream'
This should work in all browsers and force the download instead of display in browser.