I am simply trying to open a .pdf in another tab.
I start by using jQuery to post a couple of variables:
$('#resultsTable').on('click', 'tr > td > .view-pdf', function()
{
var $dataTable = $('#resultsTable').DataTable();
var tr = $(this).closest('tr');
var rowBookingNum = $dataTable.row(tr).data().JOB_REFERENCE;
var rowPartnerNum = $dataTable.row(tr).data().SHIPPER_CODE;
$.redirect('process/viewpdf.php', {'bookingnum':rowBookingNum, 'partnernum':rowPartnerNum });
});
The PHP script looks like this:
<?php
if(isset($_POST["bookingnum"]))
{
$bookingnum = $_POST["bookingnum"];
$partnernum = $_POST["partnernum"];
$dir = "D:/CargoDocsPDFs/" . $partnernum;
$file = $dir . "/" . $bookingnum . '.pdf';
if (file_exists($file))
{
header('Content-type: application/pdf');
header('Content-Disposition: inline; 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));
readfile($file);
exit;
}
}
?>
Using all of the above, I can get the .pdf to open in the same window. This causes the user to have to click the BACK button to go back to the previous screen.
I need the .pdf to open in a new tab. How can I adjust my code to make this happen?
You need to specify a target in $.redirect(url, [values, [method, [target, [traditional, [redirectTop]]]]])
See usage: http://github.com/mgalante/jquery.redirect
Desired usage:
$.redirect('process/viewpdf.php', {'bookingnum':rowBookingNum, 'partnernum':rowPartnerNum }, 'POST', '_blank');
Related
I have website which uses ajax for most of cases. I have allowed user to upload image through ajax. When user clicks on a button the image is displayed in modal through an ajax call.
Now, I want to user to begin his download by clicking on image without closing the modal or refreshing. I did tried with href. It works fine but, as I mentioned, I want to keep user on same page with modal open.
The code I have tried untill now is:
$(document).ready(function(){
var imgname;
imgname = '';
$("#modalimage").click(function(){
imgname = $("#downloadimg").val();
downloadImage(imgname);
})
})
function downloadImage(imagename){
$.ajax({
type : "POST",
url : "download.php",
data : { imagename : imagename } ,
success : function(response){
alert('success');
}
})
}
download.php code is:
if ( isset($_POST['imagename']) ) {
$filename = $_POST['imagename'];
$filepath = 'images/'.$filename;
}
echo $filepath;
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filepath));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
The problem here is when ajax make call to download.php it create a response in form of some binary codes and small image codes without initiating the download. Is it possible to download the image by ajax call?
Instead of calling it by ajax place this link:
<a href="download.php?imagename=<?php echo urldecode($imagename); ?>">
Clich here to download
</a>
where $imagename is the file path. And the link content can be the text or a thumbnail or whatever you want.
And just change the download.php code to get the image through $_GET and not $_POST and, important, remove the echo that there is in there, there should be no other content than the headers and the file content:
if ( isset($_GET['imagename']) ) {
$filename = $_GET['imagename'];
$filepath = 'images/'.$filename;
}
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=' . basename($filepath));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
You will not be redirected to the file and the file will be downloaded. No need of ajax for this.
In case you really prefer using javascript you could create the link dinamically:
$(document).ready(function(){
$("#modalimage").click(function(){
var imgname = $("#downloadimg").val();
var link = document.createElement("a");
link.download = name;
link.href = 'download.php?imagename=' + encodeURI(imgname);
link.click();
});
})
I have a PHP function which downloads differents files after clicking on a button (If we click on PDF button, it will load a pdf file, if we click on DOC button, it will load a doc file). It is the same function for both buttons.
My problem is when I download a file. If it's the PDF, IE will open an other page, and will close it and give me the choice to download the file, but if it's the DOC, IE will open an other page, and not close it.
The code is (for me) the same, I don't see any differences.
<pre>
<code>
public function lettrecadrageAction() {
$nom = $_POST['type'];
switch ($nom):
case 'Fichier DOC' :
$path = "ddl/lettre_de_cadrage.doc";
header('Content-Description: File Transfer');
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=lettre_de_cadrage.doc");
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($path));
ob_clean();
flush();
readfile($path);
break;
case 'Fichier PDF' :
$path = "ddl/lettre_de_cadrage.pdf";
header('Content-Description: File Transfer');
header('Content-Type: application/force-download');
header("Content-Disposition: attachment; filename=lettre_de_cadrage.pdf");
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($path));
ob_clean();
flush();
readfile($path);
break;
endswitch;
exit;
}
</code>
</pre>
The Js action for click
<pre>
<code>
$('.ldc_dl').click(function() {
var f = document.createElement("form");
f.method = "POST";
f.name = "form";
f.target = "_blank";
f.setAttribute('style', 'display: none;');
f.action = "http://" + document.domain + "/Exploitation/lettrecadrage/";
var fHtml = document.createElement("input");
fHtml.type = "text";
fHtml.name = "type";
fHtml.value = $(this).html();
console.log(fHtml);
var fSubmit = document.createElement("input");
fSubmit.type = "submit";
f.appendChild(fHtml);
f.appendChild(fSubmit);
document.body.appendChild(f);
f.submit();
document.body.removeChild(f);
return true;
}) </code>
</pre>
The HTML code for the buttons
<pre>
<code>
<div class="tab-pane fade" id="ldc">
<p>La lettre de cadrage est disponible en <button id="ldc_dl_doc" class="btn btn-link ldc_dl" type="button">Fichier DOC</button></p>
<p> Ou en <button id="ldc_dl_pdf" class="btn btn-link ldc_dl" type="button">Fichier PDF</button></p>
</div>
</code>
</pre>
(The buttons are 'Fichier PDF' and 'Fichier DOC')
Edit - Solution
With the help of jbl in comments, I resolved my problem, using an iframe :
var frame = document.createElement("iframe");
frame.setAttribute("src", "_blank");
and modify my form target
f.target = frame;
Content-Transfer-Encoding header is used in MIME email messages. It has no any sense to send it over HTTP.
Content-Disposition: attachment; header says the browser to save it rather then open in the browser. So instead of Content-Type: application/force-download i would suggest to use proper content-type for PDF and DOC files:
Content-Type: application/pdf
Content-Type: application/vnd.ms-word
With the help of jbl in comments, I resolved my problem, using an iframe :
var frame = document.createElement("iframe");
frame.setAttribute("src", "_blank");
and modify my form target
f.target = frame;
I currently user html2canvas to get a div as an image.
html2canvas([document.getElementById("board")],{
onrendered: function( canvas ) {
var img = canvas.toDataURL();
var request = $.ajax({
type:"POST",
url:"downloadPic.php",
data:{downloadPic : img}
});
Then, I want to download that image (to the browser default download directory)
if(isset($_POST['downloadPic'])){
$pic = $_POST['downloadPic'];
$filteredData=substr($pic, strpos($pic, ",")+1); //html2canvas adds this
$unencodeData=base64_decode($filteredData);
$filename = "downloadedPic";
header('Content-Description: File Transfer');
header('Content-Type: image/png');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
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($unencodeData));
ob_clean();
flush();
readfile($unencodeData);
}
But this doesn't seem to work. If I do a file_put_contents("downloadedPic", $unencodedData) the picture is saved on my server successfully.
Do I need the header's config differently?
I'm trying to save canvas as a image file ,users get to determine which image format to download (png or jpg), then force download the file without storing the file on the server.
This is what I got so far:
JS Script:
$.ajax(
{
type : "POST",
url : "../php/download_image.php",
data:
{
format: 'png',
dataURL: flattenCanvas.toDataURL('image/png')
}
});
PHP:
$data = $_POST['dataURL'];
$format = $_POST['format'];
$file = $file = md5(uniqid()) . '.'.$format;
$uri = substr($data,strpos($data,",")+1);
file_put_contents($file, base64_decode($uri));
if($format == 'png')
{
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));
readfile($file);
exit;
}
else {
echo "$file not found";
}
}
The code cannot force download and I have no idea why it is not working.
Any help greatly appreciated.
If you don't want to store the file on the server, you don't need to interact with the server in any way. Just let the user download the content of the canvas as described here.
I've seen this example on the documentation for PHP readfile
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
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);
exit;
}
?>
How can you make it so It download multiple files say monkey.gif and girraffe.jpg
Preferably without ZIP files...
You can't. It's not a PHP limitation, it's an HTTP/Web-Browser limitation. HTTP doesn't provide a mechanism for sending multiple files over one request.
You could, however, have some PHP script that generates multiple iframes, which would initiate one download each, and fake it that way.
the whole method seems a bit pointless as a physical file actually exists on the server. just use JavaScript to open all the file urls, if you have set the header correctly in your .htaccess file then the files will just download.
I would do something like this
<script>
var files = ['filename1.jpg', 'filename2.jpg'];
for (var i = files.length - 1; i >= 0; i--) {
var a = document.createElement("a");
a.target = "_blank";
a.download = "download";
a.href = 'http://www.example.com/path_to/images/' + files[i];
a.click();
};
</script>