I am trying to get my php script to download an image which the name of is being sent in from an ajax function in my javascript, and I think I'm using all the right headers and then I'm using readfile() to download the image, and when I preview the php when it runs with the chrome developer tools (ctrl+shift+i-> network -> XHR -> preview) all I get is a bunch of gibberish binary and my image doesn't download. Does anyone know why this is happening/how to fix it?
Here's my ajax which is just in a function that runs when a "download" button is clicked
$.ajax({
type: "POST",
url: 'requestAJAX.php',
data: {request: request, download: imageName},
success: function(){
console.log("Request Completed: " + request);
} // success
});
and here's my "requestAJAX.php"
<?php
switch ($_POST["request"]) {
case "download":
// Get parameters
$file = $_POST["download"];
$filepath = "UploadedImages/" . $file;
if(file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$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($filepath));
ob_clean();
flush();
// download
readfile($filepath);
exit;
} // if
break;
default:
echo "No request was made";
}
?>
and this is what I'm getting when I preview (not sure how it will help)
ÿØÿàJFIFHHÿâ#ICC_PROFILE0appl mntrRGB XYZ ÙacspAPPLapplöÖÓ-appldscmòdescüogXYZlwtptrXYZbXYZ¨rTRC¼cprtÌ8chad,gTRC¼bTRC¼mlucenUS&~esES&daDK.êdeDE,¨fiFI(ÜfrFU(*itIT(VnlNL(nbNO&ptBR&svSE&jaJPRkoKR#zhTWlzhCNÔruRU"¤plPL,ÆYleinen RGB-profiiliGenerisk RGB-profilProfil Générique RVBN, RGB 0×0í0Õ0¡0¤0ëu( RGB r_icÏðPerfil RGB GenéricoAllgemeines RGB-Profilfn RGB cÏðeNöGenerel RGB-beskrivelseAlgemeen RGB-profielÇ|¼ RGB Õ¸\ÓÇ|Profilo RGB GenericoGeneric RGB Profile1I89 ?#>D8;L RGBUniwersalny profil RGBdescGeneric RGB ProfileGeneric RGB ProfileXYZ Zu¬s4XYZ óRÏXYZ tM=îÐXYZ (¸6curvÍtextCopyright 2007 Apple Inc., all rights reserved.sf32BÞÿÿó&ýÿÿû¢ÿÿý£ÜÀlÿáExifMM*JR(iZHH é ¡ÿÛC
Thanks in advance for any assistance!
Related
I am creating a zip file download system in php with jquery ajax.
When the user clicks the download button, the request goes to the server and returns the filename.
I am able to download the file but it shows the name of the entire file along with the file path in console. I do not want this.
<button onclick="checkPayment(this.id)" id="filetoDownload_1">Download File</button>
Javascript
function checkPayment(data){
$.ajax({
type: 'post',
url: '../download.php',
data: data,
async: false,
success: function(result) {
let returnkd = JSON.parse(result);
if(returnkd["status"]){
$("#success").html(`<div class="card"><div class="card-body bg-white text-black">Download will start soon...</div></div>`);
setTimeout(() => {
window.location.href = returnkd["filename"];
}, 2000);
}else{
$("#error").html(`<div class="card"><div class="card-body bg-white">Something wents wrong... contact admin</div></div>`);
}
}
});
}
PHP
// wothout header
if(isset($_POST)){
some code
return array("status"=>true,"filename"=>"../folder/filename.zip");
}
// with header
if(isset($_POST)){
some code here
downloadFile($filename);
return array("status"=>true,"filename"=>"../folder/filename.zip");
}
function downloadFile($filename)
{
$filename = $filename;
$filepath = "../".$filename;
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="' . $filename . '"');
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($filepath));
ob_end_flush();
#readfile($filepath);
}
how to download file without redirecting window.location.href or showing filepath in console.
i have tried php header but it doesn't work
I am trying to download a pdf when clicking on a link.
I called function onlick of a link and in Codeigniter i wrote a function to download PDF file but when running URL ,file is downloaded but when triggered using click of link, its not working.
Controller:
function downloadpdf($pid)
{ set_time_limit(0);
$url="http://www.malayatourism.com/uploads/images/packages/pdf/$pid.pdf";
$file = basename($url);
$fp = fopen($file, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
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');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
echo "success";
}
My code ajax:
function DownLoadPdf(id)
{
url = "<?php echo base_url();?>admin/packages/downloadpdf/"+id;
$.ajax({
type:'POST',
url: url,
data : { pid : id},
success : function(response) {
console.log(response);
},
error : function(response) {
console.log("error");
}
});
}
View:
echo ' Download Attachment';
As far as ajax is concerned you cannot do that via ajax because ajax is not made for this purpose,its an asynchronous call that will give you a result. But you can do this without using any jquery, ajax at all
<a href="http://www.malayatourism.com/uploads/images/packages/pdf/$pid.pdf" download> Download Attachment</a>
Where $pid is the id you want to download the file. The download attribute will force the file to download. Cheers
My file download works great. The file is delivered correctly. But I want to make it prettier.
Is there a way to set a favicon and a window title, if I click on a html-download link to a file in a new tab?
the file is generated and streamed by php.
client part:
<a target="_blank" tabindex="0" href="/path/to/file-download/interface" >
server stream, while $file is some array holding file information:
if (file_exists($file['path'])) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $file['path']);
if( strstr($mime, "image") !== false ){
header('Content-Type: '.$mime);
header('Content-Disposition: filename='.basename($file['path']));
} else {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file['path']));
}
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['path']));
ob_clean();
flush();
readfile($file['path']);
exit;
} else {
error_log("File for download >".$file['path']."< not found.");
return false;
}
UPDATE
An additional problem is, that there is a favicon already in the root folder, but I want to show a different one.
On my website I have a JavaScript function that using PHP function creates a file locally on my server (same directory as the website files). The name of this file is known only to these JavaScript and PHP functions.
I want to open a regular 'Save As' box to the user to download this file.
Is there a way to do this using Javascript/PHP in a manner that will work for Firefox, Chrome and Explorer/Edge? (Only the Javascript/PHP know the file name)
This is the PHP example:
file_put_contents($filename,$txt);
header('content-type: application/text');
header('content-disposition: attachment; filename=' . $filename);
readfile($filename);
In chrome & firefox it saves automatically and in IE a window opens so if a user has not changed their settings by default will they see the where to save dialog regardless of the browser they're using. go to
https://support.google.com/chrome/answer/95574?hl=en-GB
For more information. You can use php code for downloading the file from your server.
header('content-type: application/[type]');
header('content-disposition: attachment; filename=yourfile.file-extension');
readfile('yourfile.file-extension');
for a large file, you can use
function readfileChunked($filename, $retbytes=true){
$chunksize = 1*(1024*1024);
$buffer = '';
$cnt = 0;
$handle = fopen($filename, 'rb');
if ($handle === false) {
return false;
}
while (!feof($handle)) {
$buffer = fread($handle, $chunksize);
echo $buffer;
ob_flush();
flush();
if ($retbytes) {
$cnt += strlen($buffer);
}
}
$status = fclose($handle);
if ($retbytes && $status) {
return $cnt; // return num. bytes delivered like readfile() does.
}
return $status;
}
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/force-download');
header('Content-Disposition: attachment; filename="'.$name.'"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: '. get_remote_size($url) );
header('Connection: close');
readfileChunked( $url );
I am trying to send files to the client via jQuery, AJAX, and PHP. I am using jQuery v1.11.2 and xampp v3.2.1,
Here is my jQuery code:
<script>
$(document).ready(function(){
$("#myBtn").click(function(){
$.ajax({ // post file name
type: "POST",
data: {
file: "testfile.xlsx"
},
url: "sendfile.php",
context: $("#result"),
success: function(data, status, xhr){
$(this).html(data);
}
});
});
});
</script>
sendfile.php:
<?php
FUNCTION send_file($name) { // function ... send file to client
OB_END_CLEAN();
$path = $name;
//cek connection if lost connection with client
IF (!IS_FILE($path) or CONNECTION_STATUS()!=0) RETURN(FALSE);
//header
//-------------------------------------------------------------
HEADER("Cache-Control: no-store, no-cache, must-revalidate");
HEADER("Cache-Control: post-check=0, pre-check=0", FALSE);
HEADER("Pragma: no-cache");
HEADER("Expires: ".GMDATE("D, d M Y H:i:s", MKTIME(DATE("H")+2, DATE("i"), DATE("s"), DATE("m"), DATE("d"), DATE("Y")))." GMT");
//set last modified property
HEADER("Last-Modified: ".GMDATE("D, d M Y H:i:s")." GMT");
HEADER("Content-Type: application/octet-stream");
HEADER("Content-Length: ".(string)(FILESIZE($path)));
HEADER("Content-Disposition: inline; filename=$name"); // file
HEADER("Content-Transfer-Encoding: binary\n");
//-----------------------------------------------------------------
IF ($file = FOPEN($path, 'rb')) { // send file
WHILE(!FEOF($file) and (CONNECTION_STATUS()==0)) {
PRINT(FREAD($file, 1024*8));
FLUSH();
}
FCLOSE($file);
}
RETURN((CONNECTION_STATUS()==0) and !CONNECTION_ABORTED());
}
// send file
if(!send_file($_POST['file'])){
echo "error.";
}
When I press the button no files received instead of random sentences in #result
If I use directly in PHP functions are working properly
send_file("testfile.xlsx");
Are there more effective methods?
if you're looking for another method similar to that,
try using 'uploadify' its free and easy --> http://www.uploadify.com/demos/