Call file php by ajax to download a file - javascript

I have one PHP file and other JavaScript. In JavaScript, I pass the variable with location of place where the file exists but on the PHP side doesn't recognize and doesn't properly download the file.
Code of JavaScript:
var nameFile = oEvent.getParameters().listItem.getTitle();
var directory = "C:/xampp/htdocsui5launchpad/WebContent/documents/";
window.location =directory;
$.ajax({
url: 'http://localhost/ui5launchpad/WebContent/php/downloadPDF.php',
type: 'POST',
datatype: "json",
data: { album: nameFile },
success: function (response, data, xhr) {
window.location = 'http://localhost/ui5launchpad/WebContent/php/downloadPDF.php';
},
error: function (response) {
console.log("Error in PHP, downloadPDF.php ");
}
});
PHP code:
if(isset($_POST["album"])){
$name = $_POST["album"];
}
$dir = "C:/xampp/htdocs/ui5launchpad/WebContent/documents/";
$file = $dir . $name;
if( isset($file)) {
//echo $file;
if (file_exists($file)) {
//echo $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;
}
}
Can you help me, please ?
Thanks

You don't need to use ajax to download a file. Just link the file direct to the browser.
In the link tag put the attribute like this:
<a href="http://example.com/file.pdf" download>Download</a>

Related

download zip file in php and ajax without location.href

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

Trying to download file from remote server using Ajax with Codeigniter not working

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

Downloading file using php and ajax

I'm trying to write a script to download a file. But when I click "Download" nothing happens. I'm using Laravel for my project. This is the function:
public function downloadUserFile(){
$userid = Auth::id();
$result = $_POST['filename'];
$query = File::where('filename', $result)->where('userid', $userid)->get();
foreach($query as $queryResult){
$mimeType = $queryResult->mimetype;
$filepath = $queryResult->filePath;
$filesize = $queryResult->filesize;
if (file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: ' . $mimeType);
header('Content-Disposition: attachment; filename="'.basename($filepath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . $filesize);
ob_clean();
flush();
readfile($filepath);
exit;
}
}
}
And the ajax:
if(key === "download") {
var classElements = document.querySelectorAll("tr.ui-selected td.filename");
var csrf = $('input[name=_token]').val();
for(var x = 0;x < classElements.length;x++){
var result;
result = classElements[x].innerHTML;
$.ajax({
async: true,
method: 'POST',
url: '../public/downloadfile',
data: { filename: result, "_token": csrf }
});
};
}
The ajax response and the PHP don't give me errors and I can't understand why nothing actually happens. What could be the problem?

Download an image with an ajax request

I have some files on my PHP server inside uploads folder. My problem is the following: I want to send a JSON asynchronous request from my client as to choose one of these files and create with this an image element as to display it in the browser.
JS code
var file_name="test.jpg";
$.ajax({
method:"POST",
dataType:"json",
url:"retrieve_photo.php",
data:{name:file_name},
success: function(data) {
var new_thumb = document.createElement("img");
document.getElementById('dragarea').appendChild(new_thumb);
...
}
})
PHP code (retrieve_photo.php):
<?php
$ds = DIRECTORY_SEPARATOR;
$storeFolder="uploads";
$file_name=$_POST[name];
$files = glob($storeFolder.$ds.$file_name);
if ( false!==$files ) {
....
}
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
?>
I do not know what to write as $result feeds data the right way. I 've tried
$result=readfile($storeFolder.$ds.$file_name);
but maybe not correctly.As to conclude I want to use data as to display an image to my browser.
Thank you
Maybe will be better do something like that?:
var image = new Image();
image.src = "blabla";
$(image).on('load', function(){
//do what you want
})
Why do you even use AJAX? Maybe i don't understand)
Since you don't use algorithm or functions in your PHP, you can do everything by Javascript / Jquery :
var img = $("<img />").attr('src', 'uploads/'+ file_name)
.on('load', function() {
if (!this.complete || typeof this.naturalWidth == "undefined") {
alert('Image not found');
} else {
$("#dragarea").append(img);
}
});
document.getElementByI('dragarea').appendChild(new_thumb);
Мaybe you mean? document.getElementById('dragarea').appendChild(new_thumb);
document.getElementById('dragarea').appendChild(new_thumb);
try this in your retrieve_photo.php
$filename = "test.jpg";
//Make sure $filename contains the appropriate path of the photo
$size = getimagesize($filename);
$file = $filename;
if ($size) {
header("Content-type:". $size['mime']);
header("Content-Length: " . filesize($file));
header("Content-Disposition: attachment; filename=$filename");
header('Content-Transfer-Encoding: base64');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header("Content-Type: application/force-download");
readfile($file);
exit;
}

PHP File Download with ajax Problems

i am this problem of not being able to download image from server to my PC(No saving prompt ) , no error message have been shown
The output i am receiving is some unreadable code from the google chrome inspect element
Thanks in advance
Javascript
function Download(id) {
console.log(id);
$.ajax({
type: 'post',
url: 'DownloadRequest.php',
data: {filename: id.trim()},
});
}
DownloadRequest.php File
<?php
$file = $_POST['filename'];
header ("Content-Type: application/download");
header ("Content-Disposition: attachment; filename=$file");
header("Content-Length: " . filesize("$file"));
$fp = fopen("$file", "r");
fpassthru($fp);
?>
Solution
function Download(id) {
window.location="DownloadRequest.php?url="+id.trim();
}
<?php
$file = $_GET['url'];;
header ("Content-Type: application/download");
header ("Content-Disposition: attachment; filename=$file");
header("Content-Length: " . filesize("$file"));
$fp = fopen("$file", "r");
fpassthru($fp);
?>
you can try like this, instead of using ajax,
window.location="DownloadRequest.php?filename";
Final code,
function Download(id) {
console.log(id);
window.location="DownloadRequest.php?filename";
}

Categories

Resources