Download an image with an ajax request - javascript

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;
}

Related

Using an AJAX call to display base64 image data via PHP

I'm wanting to render an image using an AJAX call but I’m having trouble returning an image from the server as a base24 string via PHP.
In the renderImage function below the test image data 'R0lGODlhCw...' is displaying correctly but the image data coming from the AJAX call is not.
I want to use AJAX instead of just outputting the image file contents into the src attribute because I eventually want to add authorization headers to the PHP file.
I think I’m missing something in the PHP file and some headers in the ajax call?
PHP file: image.php
<?php
header("Access-Control-Allow-Origin: *");
$id = $_GET["id"];
$file = '../../upload/'.$id;
$type = pathinfo($file, PATHINFO_EXTENSION);
$data = file_get_contents($file);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return $base64;
?>
JS
function renderImage(id) {
//return "R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
return $.ajax({
url: '[server URL]/image.php',
data:{"id":id},
type: 'GET',
});
};
$('.feedImage').each(async function() {
try {
const res = await renderImage($(this).data("id"));
$(this).attr("src","data:image/gif;base64," + res);
} catch(err) {
console.log("error"+err);
}
});
raw image obtained from How to display an image that we received through Ajax call?
First you should fix your php image rendering
<?php
header("Access-Control-Allow-Origin: *");
$id = $_GET["id"];
$file = '../../upload/'.$id;
$type = pathinfo($file, PATHINFO_EXTENSION);
$data = file_get_contents($file);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo json_encode(array('id' => $base64));
?>
Then your javascript, as you already defined the data image type there is no need to repeat it on the javascript.
function renderImage(id) {
//return "R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
return $.ajax({
url: '[server URL]/image.php',
data:{"id":id},
type: 'GET',
});
};
$('.feedImage').each(async function() {
try {
const res = await renderImage($(this).data("id"));
$(this).attr("src", res);
} catch(err) {
console.log("error"+err);
}
});

How to execute generate CSV File in php?

I want to generate a csv file with a dynamic filename which came from the values I got using an ajax jquery request. These values will be used as filename for my generated csv file. My program does not generate the csv file. What should I do for the csv file to be generated?
I am a newbie when it comes to php and especially AJAX and Jquery so I am still a bit confused on how an AJAX request works.
I'm using a free trial version of Sublime IDE and localhost for php. The program displays the contents of the csv file through an alert box but it doesn't generate a csv file.
This is my jquery ajax request file:
var selectedLanguage = $('#selectLanguage').val();
var length;
length = selectedLanguage.length;
for (var i = 0; i < length; i++)
{
var selectedLanguage = $('#selectLanguage').val();
$.ajax({
crossDomain: true,
async: false,
url: "downloadFile.php",
type: "GET",
data: {"seLang": selectedLanguage[i]},
success: function(data)
{
alert(data);
location.reload();
}
});
}
This is my downloadFile.php code:
<?php
$id="";
if(isset($_GET['seLang'])){
$id = $_GET['seLang'];
$filename = "File_".$id.".csv";
$f = fopen('php://memory', 'w');
//set headers for column
$fields = array('Content1', 'Content2', 'Content3','Content4');
fputcsv($f, $fields, ',');
fseek($f, 0);
header('Content-Encoding: UTF-8');
header('Content-type: text/csv; charset=UTF-8');
header('Content-Disposition: attachment; filename="' . $filename . '";');
fpassthru($f);
}
else
{
echo "<script type='text/javascript'>alert('Empty');</script>";
}
?>
Edit 1:
Thank you Prvn and Sunday Johnson for trying to help. Although, I've found the actual problem. I've read from another post in this site that it is isn't possible to download the generated csv file using AJAX. What else can I do for me to download a csv file?
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');
$fields = array('Content1', 'Content2', 'Content3','Content4');
$fp = fopen('php://output', 'wb');
foreach ( $fields as $line ) {
$val = explode(",", $line);
fputcsv($fp, $val);
}
fclose($fp);
Output
One comment about the Ajax code, why are you iterating over the value?
About the php code, use this instead:
<?php
$id="";
if(isset($_GET['seLang'])){
$id = $_GET['seLang'];
$filename = "File_".$id.".csv";
$f = fopen($filename, 'w');
//set headers for column
$fields = array('Content1', 'Content2', 'Content3','Content4');
fputcsv($f, $fields, ',');
fclose($f);
}
else
{
echo "<script type='text/javascript'>alert('Empty');</script>";
}
?>

JavaScript Search bar to display results after user input

I have a webpage that displays a list of my local files, and I have a search bar that goes through the list of files and highlights the first match.
However, how can I display the files only when a user searches for a filename. So instead of all the files showing, I'd only like the files that match the search criteria to be returned.
PHP, JavaScript, jQuery is totally an option here if anyone can help in that area.
testexec.php:
<?php
$path = '/var/www/html/'; //get list of files
$files = scandir($path);
//display the links
foreach($files as $file) {
if($file != '.' && $file != '..') {
echo '<div> '.$file.'</div>';
}
}
?>
readfile.php:
<?php
// PHP script to allow the file to be downloaded
$filename = $_GET['file'];
if (file_exists($filename)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;
filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($filename);
exit;
}
?>
//JavaScript for searchbar
function FindNext() {
var str = document.getElementById ("livesearch").value;
if (str == "") {
alert ("Please enter some text to search!");
return;
}
var supported = false;
var found = false;
if (window.find) { // Firefox, Google Chrome, Safari
supported = true;
// if some content is selected, the start position of the search
// will be the end position of the selection
found = window.find (str);
} else {
if (document.selection && document.selection.createRange) { // Internet Explorer, Opera before version 10.5
var textRange = document.selection.createRange ();
if (textRange.findText) { // Internet Explorer
supported = true;
// if some content is selected, the start position of the search
// will be the position after the start position of the selection
if (textRange.text.length > 0) {
textRange.collapse (true);
textRange.move ("character", 1);
}
found = textRange.findText (str);
if (found) {
textRange.select ();
}
}
}
}
if (supported) {
if (!found) {
alert ("The following text was not found:\n" + str);
}
}
else {
alert ("Your browser does not support this example!");
}
}
This is the simplest idea.
Frontend
index.html
$('input').keydown(function(e) {
var str = $(this).val();
alert(str);
$.get("/search.php?query=" + str, function(data) {
$('.result').html(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>File search and download</h3>
<input name="filename" placeholder="file name" class="kw"/>
<div class="result">
</div>
Backend
search.php
<?php
// You need code search file
// after search $files
$str = '';
foreach($files as file) {
$str .= ''.$file.' <br>'
}
return $str;
?>
readfile.php
<?php
// PHP script to allow the file to be downloaded
$filename = $_GET['file'];
if (file_exists($filename)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;
filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
readfile($filename);
exit;
}
?>
this really easy. you just need to use event keyup and some code fix
index.php
<input type="text" id="searchbar" placeholder="search file"> <span id="loading" style="display:none;">loading</span>
<div id="result"></div>
<script src="../../vendor/jquery/jquery-3.2.1.min.js"></script>
<script>
$(function(){
$('#searchbar').keyup(function(){//event after user release keyboard
var val = $(this).val();
if(val.length >= 2){//min 2 words to start find
$.ajax({
url: 'search.php',
type: 'POST',
dataType: 'json', //we use json
data: {keyword: val},
beforeSend: function(){
$('#loading').show();
},
success: function(d){
if(d.ok==1){
$('#result').html(d.list);
}else{
alert(d.msg);
}
$('#loading').hide();
},
error: function(d){
alert('error');
$('#loading').hide();
}
});
}
})
});
</script>
search.php
<?php
$path = 'C:/xampp/htdocs/';
$keyword = isset($_POST['keyword']) ? $_POST['keyword'] : '';
$scan = scandir($path);
$result = array('ok'=>0); //prepare output cz we will use json instead text/html
if($scan !== false){
$result['ok']=1;
$list = array();
foreach($scan as $file){
if(is_file($path.$file)){ //only file
if(preg_match('/'.$keyword.'/', $file)) //is file containts keyword?
$list[] = '<div>'.$file.'</div>';
}
}
$result['list'] = count($list) == 0 ? 'no file match': $list;
}else
$result['msg'] = "failed open dir";
echo json_encode($result);
readfile.php
<?php
// PHP script to allow the file to be downloaded
$filename = $_GET['file'];
$path = 'C:/xampp/htdocs/';
$fullPath = $path.$filename; //you need this
if (file_exists($fullPath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fullPath));
readfile($fullPath);
exit;
}
?>
There are many ways to do that.
I would suggest that:
Make your PHP answer a JSON with the files that match a given criteria. So you will ask to the PHP, passing in POST data ou QUERY string the "text" that is being search. It will give you only the files that matches.
In you html file (could be another PHP as well), you will call ajax (you can use jQuery) to the page above everytime user changes the search text. It's good thing to "throttle" (see lodash/underscore library) (wait some time waiting for more key presses).
After receiving the JSON with the files that matches, build dynamically you table (or another way you want).
search.php:
<?php
header('Content-Type: application/json');
$path = '/var/www/html/'; //get list of files
$files = scandir($path);
$search = $_GET['search'];
$links = array();
foreach ($files as $file) {
if($file != '.' && $file != '..' && strpos(strtolower($file), strtolower($search)) !== false) {
array_push($links, array(
"name" => $file,
"url" => "readfile.php?file=" . urlencode($file)
));
}
}
echo json_encode($data);
?>
index.php / index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-2.2.4.min.js">
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js">
</head>
<body>
<input id="searchbox" type="text" placeholder="search for files" />
<div id="results">
</div>
<script>
$(function () {
var searchbox = $("#searchbox");
var results = $("#results");
var doSearch = _.throttle(function () {
var searchtext = searchbox.val();
$.ajax({
type: 'get',
url: 'search.php',
dataType: "json",
data: {
search: searchtext
}
}).done(function (response) {
results.html(response.reduce(function (html, item) {
return html + '<div>' + item.name + '</div>';
}, ''));
});
}, 200);
searchbox.on('keydown', doSearch);
});
</script>
</body>
</html>

Call file php by ajax to download a file

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>

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