Add custome column in PrimeNG exprot as CSV - javascript

I want to add some custom columns in the PrimeNG table, could you please guide me, that how we can add some other field in export CSV but that column is not added in my Dashboard table.

There is a sample code that saves the table by column
as a base I used original prime ng implementation method exportCSV({selectionOnly:true}) (export selected row)
For full demo see https://stackblitz.com/edit/angular-table-ecport-by-column
the key method is exportCSV
exportCSV(table: Table){
var _this = this;
var selColumns = this.selectedColumns;
var csv = '';
var exportFilename = 'download';
var csvSeparator = ',';
//headers
for (var i = 0; i < selColumns.length; i++) {
var column = selColumns[i];
if (column.exportable !== false && column.field) {
csv += '"' + (column.header || column.field) + '"';
if (i < (selColumns.length - 1)) {
csv += csvSeparator;
}
}
}
//body
this.carsData.forEach(function (record, i) {
csv += '\n';
for (var i_1 = 0; i_1 < table.columns.length; i_1++) {
const column = table.columns[i_1];
var showColumn = selColumns.find(x=> column.field === x.field);
if (column.exportable !== false && column.field && showColumn != null) {
// var cellData = JSON.stringify(record, column.field);
var cellData;
Object.keys(record).forEach(key =>{
if(key === column.field){
cellData = record[key];
}
})
// console.log(cellData);
if (cellData != null) {
if (table.exportFunction) {
cellData = table.exportFunction({
data: cellData,
field: column.field
});
}
else
cellData = String(cellData).replace(/"/g, '""');
}
else
cellData = '';
csv += '"' + cellData + '"';
if (i_1 < (table.columns.length - 1)) {
csv += csvSeparator;
}
}
}
});
var blob = new Blob([csv], {
type: 'text/csv;charset=utf-8;'
});
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, exportFilename + '.csv');
}
else {
var link = document.createElement("a");
link.style.display = 'none';
document.body.appendChild(link);
if (link.download !== undefined) {
link.setAttribute('href', URL.createObjectURL(blob));
link.setAttribute('download', exportFilename + '.csv');
link.click();
}
else {
csv = 'data:text/csv;charset=utf-8,' + csv;
window.open(encodeURI(csv));
}
document.body.removeChild(link);
}
}

Related

How to export desired fields from PHP array to JSON/CSV in Javascript

I'm a newbie about php and javascript and sorry for my bad English. I've searched and read many threads about this but nothing works for me.
I need to understand how I can export some fields of a json files into a CSV or excel with some of that fields and not all, ready to download.
I managed to get a json output with an array of data and print it in the console by clicking on a button. This is a script inside a php file.
Now I need to convert this output in CSV and able to download it.
Here js code where I stored the array in var json :
<a id="csv_btn" class= "btn btn-primary btn-sm pull-right"
onclick="download_csv()">Download CSV</a>
<div class="js-search-box"></div>
<script type="text/javascript">
var json = <?php echo json_encode($outjson); ?>;
function download_csv () {
var formId = document.getElementById("csv_btn");
window.alert("Do yow want to download CSV?");
console.log(json);
}
</script>
In the images attached, there is the output after clicking on download.
Thanks in advance
enter image description here
enter image description here
EDIT:
After many attempts, I've found a code working quite well; thanks to Danny Pule found at this link
Now, I'm trying to figure out how to create a filter to exclude or include certain fields and get the CSV with the wanted fields. Also, if someone could explain me how to extract data from a field that print [object Object] inside this json file (i.e. at "machine" field there is another array)
enter image description here
The code below:
<!--gabri-->
<a id="csv_btn" class= "btn btn-primary btn-sm pull-right" onclick="exportCSVFile(headers, itemsFormatted, fileTitle)">Download CSV</a>
<div class="js-search-box"></div>
<script type="text/javascript">
var datajson = <?php echo json_encode($outjson); ?>;
//download_csv(datajson);
function convertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
window.alert("Do yow want to download CSV?");
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
function exportCSVFile(headers, items, fileTitle) {
if (headers) {
items.unshift(headers);
}
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
var csv = this.convertToCSV(jsonObject);
var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
console.log(datajson);
}
}
}
var headers = {
label: 'Project Name'.replace(/,/g, ''), // remove commas to avoid errors
id: "id".replace(/,/g, ''),
active: "active",
start_date: "Start Date".replace(/,/g, ''),
year:"Year",
coord: "Coord",
perc: "perc",
plants:"Total Plants",
done: "Plants done",
machine: "Machine"
};
//itemsNotFormatted = [];
var obj = JSON.parse([datajson]);
var values = Object.keys(obj).map(function (key) { return obj[key]; });
//var values = Object.keys(obj).forEach(key => { console.log(key, obj[key]);});
console.log(values);
var itemsFormatted = values;
// format the data
/*itemsNotFormatted.forEach((item) => {
itemsFormatted.push({
label: item.label.replace(/,/g, ''), // remove commas to avoid errors,
id: item.id,
start_date: item.start_date,
coord: item.coord,
perc: item.perc,
plants: item.plants,
done: item.done,
machine: item.machine
});
});
*/
var fileTitle = 'monitor-report'; // or 'my-unique-title'
//exportCSVFile(headers, itemsFormatted, fileTitle); // call the exportCSVFile() function to process the JSON and trigger the download
</script>
This is the datajson I get from php
[{"label":"garbuiodiadoragrande","id":2176216,"active":0,"start_date":"23 mag, 2018","end_date":null,"perc":0.061996280223187,"plants":1613,"done":1,"machines":[{"label":"Trattore test 02 2016","id":3003}],"client":null,"client_id":null,"source":{"label":"Trattore test 02 2016","id":3003},"center_lat":45.777920164083,"center_lon":12.007139535756,"page":"\/customer\/projects\/2176216\/"},{"label":"prova","id":2176008,"active":0,"start_date":"21 mag, 2018","end_date":null,"perc":0.44247787610619,"plants":3842,"done":17,"machines":[{"label":"Trattore test 02 2016","id":3003}],"client":null,"client_id":null,"source":{"label":"Trattore test 02 2016","id":3003},"center_lat":43.830309706033,"center_lon":11.206148940511,"page":"\/customer\/projects\/2176008\/"}
and in the image attached below is the result I got from Object.map in the console.log (values), but I'm not sure to be in the right way and I'm quite confused.
enter image description here
Thanks for any suggestions
EDIT:
Ok, I got a code working and filtering the desired field
<script type="text/javascript">
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
// For the time now
Date.prototype.timeNow = function () {
return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}
var datetime = " # " + new Date().today() + " # " + new Date().timeNow();
var fileTitle = 'monitor-report'+ datetime; // or 'my-unique-title'
var datajson = <?php echo json_encode($outjson); ?>;
var itemsFormatted = JSON.parse([datajson]);
//download_csv(datajson);
function convertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
window.alert("Do yow want to download CSV?");
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
function exportCSVFile(headers, items, fileTitle) {
if (headers) {
items.unshift(headers);
}
// Convert Object to JSON
var jsonObject = JSON.stringify(items,
['label',
'id',
'start_date',
'year',
'end_date',
'perc',
'plants',
'done']);
var csv = this.convertToCSV(jsonObject);
var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
console.log(jsonObject);
}
}
}
var headers = {
label: 'Project Name'.replace(/,/g, ''), // remove commas to avoid errors
id: "id",
active: "active",
start_date: "Start Date".replace(/,/g, ''),
year:"Year",
end_date:"End Date",
perc: "perc",
coord: "Coord",
plants:"Total Plants",
done: "Plants done",
};
//console.log(datajson);
</script>
But I can't figured out how to extract another array inside the main array. Here in "machines":[{"label":"Trattore test 02 2016","id":3003}], I need label and id.
Anyone could help me)
[{"label":"garbuio diadoragrande","id":2176216,"active":0,"start_date":"23 mag,2018",
"end_date":null,"perc":0.061996280223187,"plants":1613,"done":1,
"machines":[{"label":"Trattore test 02 2016","id":3003}],
"client":null,"client_id":null,"source":{"label":"Trattore test 02 2016","id":3003},"center_lat":45.777920164083,"center_lon":12.007139535756,"page":"\/customer\/projects\/2176216\/"},
Finally I got a working code. Probably it's not perfect but it works!
Here is the code if it might be useful for someone.
Thanks to the community
<script type="text/javascript">
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
// For the time now
Date.prototype.timeNow = function () {
return ((this.getHours() < 10)?"0":"") + this.getHours() +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}
var datetime = " # " + new Date().today() + " # " + new Date().timeNow();
var fileTitle = 'Report_Monitor'+ datetime; // or 'my-unique-title'
var datajson = <?php echo json_encode($outjson); ?>;
var itemsFormatted = JSON.parse([datajson]);
//var itemsFormatted = obj;
function convertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
window.alert("Do yow want to download CSV?");
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
function exportCSVFile(headers, items, fileTitle) {
if (headers) {
items.unshift(headers);
}
// Convert Object to JSON
var jsonObject = JSON.stringify(items,
['label',
'id',
"start_date".replace(/,/g, ' '),
'end_date',
'perc',
'plants',
'done',
'center_lat',
'center_lon']);
var jsonObjectFiltered = jsonObject.replace(/,(?!["{}[\]])/g, "");
console.log(jsonObjectFiltered);
var csv = this.convertToCSV(jsonObjectFiltered).replace(/null/g,"0");
var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
console.log(jsonObject);
}
}
}
var headers = {
label: 'Project Name', // remove commas to avoid errors
id: 'id',
active: 'active',
start_date: 'Start Date',
//year:'Year',
end_date:'End Date',
perc: 'Percentage',
plants:'Total Stakes',
done: 'Stakes Done',
center_lat: 'Lat',
center_lon: 'Lon'
};
//console.log(datajson);
</script>

Export CSV data with # character in JavaScript does not work

I export JSON data to CSV format and download it with JavaScript. Everything works fine except if the data has the hash sign #. The function does not export all data, for example:
this is my first C# lesson in the academy, it exports only this is my first C and ignore the rest of it.
This is my code
this.handleRow = function (row) {
var finalVal = '';
for (var j = 0; j < row.length; j++) {
var innerValue = "";
if (row[j]) {
innerValue = row[j].toString();
}
if (row[j] instanceof Date) {
innerValue = row[j].toLocaleString();
}
var result = innerValue.replace(/"/g, '""');
if (result.search(/("|,|\n)/g) >= 0) {
result = '"' + result + '"';
}
if (j > 0) finalVal += ',';
finalVal += result;
}
return finalVal + '\n';
};
this.jsonToCsv = function (filename, rows) {
var csvFile = '';
for (var i = 0; i < rows.length; i++) {
csvFile += this.handleRow(rows[i]);
}
var blob = new Blob([csvFile], { type: 'text/csv;charset=utf-8;'});
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, filename);
} else {
var link = $window.document.createElement("a");
if (typeof link.download === "string") {
link.setAttribute("href", "data:text/csv;charset=utf-8,%EF%BB%BF" + encodeURI(csvFile));
link.setAttribute("download", filename);
link.style.visibility = 'hidden';
$window.document.body.appendChild(link);
link.click();
$window.document.body.removeChild(link);
}
}
};
encodeURI encodes characters which are forbidden in a URI, not ones which have special meaning.
The # won't be encoded but it starts the fragment identifier portion of the URI.
Use encodeURIComponent instead.

How could I speed up this exporting data function using javascript

I have a feature for users to be able to export the database information. But if the user choose all options to export it takes 1 minute or more to download the .csv file. I'm only including 1 part of the if statement, where I'm pulling in all the data.
here it is:
function exportTheData() {
//get the data for data array
if(exportVolumeData == 1) {
for(j=0; j<plantData1.length; j++) {
i = plantData["MergeKey_lvl00"].indexOf(plantData1["MergeKey_lvl00"][j]);
data.push(plantData["PlantName"][i]);
if(statesExport == 1) {
countyindex = counties["CountyId"].indexOf(plantData["LocationId"][i]);
stateid = counties["StateId"][countyindex];
statename = states["StateName"][states["StateId"].indexOf(stateid)];
data.push(statename);
}
if(countyExport == 1) {
countyindex = counties["CountyId"].indexOf(plantData["LocationId"][i]);
countyname = counties["CountyName"][countyindex];
data.push(countyname);
}
if(basinsExport == 1) {
countyindex = counties["CountyId"].indexOf(plantData["LocationId"][i]);
subbasinid = counties["SubBasinId"][countyindex];
subbasinindex = basinSub["SubBasinId"].indexOf(subbasinid);
basinid = basinSub["BasinId"][subbasinindex];
basinindex = basin["BasinId"].indexOf(basinid);
basinname = basin["BasinName"][basinindex];
data.push(basinname);
}
if(subBasinsExport == 1) {
countyindex = counties["CountyId"].indexOf(plantData["LocationId"][i]);
subbasinid = counties["SubBasinId"][countyindex];
subbasinindex = basinSub["SubBasinId"].indexOf(subbasinid);
subbasinname = basinSub["SubBasinName"][subbasinindex];
data.push(subbasinname);
}
if(paddsExport == 1) {
countyindex = counties["CountyId"].indexOf(plantData["LocationId"][i]);
subpaddid = counties["SubPaddId"][countyindex];
subpaddindex = paddSub["SubPaddId"].indexOf(subpaddid);
paddid = paddSub["PaddId"][subpaddindex];
paddindex = padd["PaddId"].indexOf(paddid);
paddname = padd["PaddName"][paddindex];
data.push(paddname);
}
if(subPaddsExport == 1) {
countyindex = counties["CountyId"].indexOf(plantData["LocationId"][i]);
subpaddid = counties["SubPaddId"][countyindex];
subpaddname = paddSub["SubPaddName"][paddSub["SubPaddId"].indexOf(subpaddid)];
data.push(subpaddname);
}
if(fullNameExport == 1) {
companyindex = getCompanyInfo["MergeKey_lvl00"].indexOf(plantData["OperatorId"][i]);
fullname = getCompanyInfo["FullName"][companyindex];
data.push(fullname);
}
if(shortNameExport == 1) {
companyindex = getCompanyInfo["MergeKey_lvl00"].indexOf(plantData["OperatorId"][i]);
shortname = getCompanyInfo["ShortName"][companyindex];
data.push(shortname);
}
if(tickerExport == 1) {
companyindex = getCompanyInfo["MergeKey_lvl00"].indexOf(plantData["OperatorId"][i]);
ticker = getCompanyInfo["Ticker"][companyindex];
data.push(ticker);
}
volumeindex = plantData1["MergeKey_lvl00"].indexOf(plantData["MergeKey_lvl00"][i]);
startdate = plantData1["MonthStartDate"][volumeindex];
volumetypeindex = plantData2["VolumeTypeId"].indexOf(plantData1["VolumeTypeId"][j]);
volumetype = plantData2["VolumeType"][volumetypeindex];
volumeunit = plantData2["Unit"][volumetypeindex];
volume = plantData1["Volume"][volumeindex];
data.push(startdate);
data.push(volumetype);
data.push(volumeunit);
data.push(volume);
}
/* * Convert our data to CSV string */
var CSVString = prepCSVRow(titles, titles.length, '');
CSVString = prepCSVRow(data, titles.length, CSVString);
/* * Make CSV downloadable*/
var downloadLink = document.createElement("a");
var blob = new Blob(["\ufeff", CSVString]);
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = "data.csv";
/** Actually download CSV */
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
Here is where I convert the data array to csv string:
function prepCSVRow(arr, columnCount, initial) {
var row = ''; // this will hold data
var delimeter = ','; // data slice separator, in excel it's `;`, in usual CSv it's `,`
var newLine = '\r\n'; // newline separator for CSV row
/* * Convert [1,2,3,4] into [[1,2], [3,4]] while count is 2
* #param _arr {Array} - the actual array to split
* #param _count {Number} - the amount to split
* return {Array} - splitted array */
function splitArray(_arr, _count) {
var splitted = [];
var result = [];
_arr.forEach(function(item, idx) {
if ((idx + 1) % _count === 0) {
splitted.push('"' + item + '"');
result.push(splitted);
splitted = [];
} else {
splitted.push('"' + item + '"');
}
});
return result;
}
var plainArr = splitArray(arr, columnCount);
// don't know how to explain this
// you just have to like follow the code
// and you understand, it's pretty simple
// it converts `['a', 'b', 'c']` to `a,b,c` string
plainArr.forEach(function(arrItem) {
arrItem.forEach(function(item, idx) {
row += item + ((idx + 1) === arrItem.length ? '' : delimeter);
});
row += newLine;
});
return initial + row;
}
Any idea on how I could speed this up? We have over 6,000 rows of data in the database. Thanks!
Changing the data.push.. to data[data.length] = .. has made the function a lot faster. Also, I created variables for countyindex and companyindex instead of calling it multiple times in the same function.
Also, cleaning up the last part of the function really helped:
/* * Convert our data to CSV string */
var CSVString = prepCSVRow(titles, titles.length);
CSVString += prepCSVRow(data, titles.length);
/* * Make CSV downloadable*/
var downloadLink = document.createElement('a'),
blob = new Blob(['\ufeff', CSVString]);
downloadLink.href = URL.createObjectURL(blob);
downloadLink.download = 'data.csv';
/** Actually download CSV */
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);

Add extension to exported CSV file

I have a script that exports data from page to csv and other formats. The problem is that when saved to csv, the script exports it as a file without extension. Also, I can't change the file's name - download.
Here is the part of the function that is for the csv export:
(function($){
$.fn.extend({
tableExport: function(options) {
var defaults = {
separator: ',',
ignoreColumn: [],
tableName:'yourTableName',
type:'csv',
pdfFontSize:14,
pdfLeftMargin:20,
escape:'true',
htmlContent:'true',
consoleLog:'true'
};
var options = $.extend(defaults, options);
var el = this;
if(defaults.type == 'csv' || defaults.type == 'txt'){
// Header
var tdData ="";
$(el).find('thead').find('tr').each(function() {
tdData += "\n";
$(this).filter(':visible').find('th').each(function(index,data) {
if ($(this).css('display') != 'none'){
if(defaults.ignoreColumn.indexOf(index) == -1){
tdData += '"' + parseString($(this)) + '"' + defaults.separator;
}
}
});
tdData = $.trim(tdData);
tdData = $.trim(tdData).substring(0, tdData.length -1);
});
// Row vs Column
$(el).find('tbody').find('tr').each(function() {
tdData += "\n";
$(this).filter(':visible').find('td').each(function(index,data) {
if ($(this).css('display') != 'none'){
if(defaults.ignoreColumn.indexOf(index) == -1){
tdData += '"'+ parseString($(this)) + '"'+ defaults.separator;
}
}
});
//tdData = $.trim(tdData);
tdData = $.trim(tdData).substring(0, tdData.length -1);
});
//output
if(defaults.consoleLog == 'true'){
console.log(tdData);
}
var base64data = "base64," + $.base64.encode(tdData);
window.open('data:application/'+defaults.type+';filename=exportData;' + base64data);
}
How can I add .csv to the exported file and eventually rename the exported file?

PHP not working when in Subfolder

I am using a File Manager jquery script, here's the first portion:
$(function(){
var filemanager = $('.filemanager'),
Here is the script.js:
$(function(){
var filemanager = $('.filemanager'),
breadcrumbs = $('.breadcrumbs'),
fileList = filemanager.find('.data');
// Start by fetching the file data from scan.php with an AJAX request
$.get("phpfiles/scan.php", function(data) {
var response = [data],
currentPath = '',
breadcrumbsUrls = [];
var folders = [],
files = [];
// This event listener monitors changes on the URL. We use it to
// capture back/forward navigation in the browser.
$(window).on('hashchange', function(){
goto(window.location.hash);
// We are triggering the event. This will execute
// this function on page load, so that we show the correct folder:
}).trigger('hashchange');
// Hiding and showing the search box
filemanager.find('.search').click(function(){
var search = $(this);
search.find('span').hide();
search.find('input[type=search]').show().focus();
});
// Listening for keyboard input on the search field.
// We are using the "input" event which detects cut and paste
// in addition to keyboard input.
filemanager.find('input').on('input', function(e){
folders = [];
files = [];
var value = this.value.trim();
if(value.length) {
filemanager.addClass('searching');
// Update the hash on every key stroke
window.location.hash = 'search=' + value.trim();
}
else {
filemanager.removeClass('searching');
window.location.hash = encodeURIComponent(currentPath);
}
}).on('keyup', function(e){
// Clicking 'ESC' button triggers focusout and cancels the search
var search = $(this);
if(e.keyCode == 27) {
search.trigger('focusout');
}
}).focusout(function(e){
// Cancel the search
var search = $(this);
if(!search.val().trim().length) {
window.location.hash = encodeURIComponent(currentPath);
search.hide();
search.parent().find('span').show();
}
});
// Clicking on folders
fileList.on('click', 'li.folders', function(e){
e.preventDefault();
var nextDir = $(this).find('a.folders').attr('href');
if(filemanager.hasClass('searching')) {
// Building the breadcrumbs
breadcrumbsUrls = generateBreadcrumbs(nextDir);
filemanager.removeClass('searching');
filemanager.find('input[type=search]').val('').hide();
filemanager.find('span').show();
}
else {
breadcrumbsUrls.push(nextDir);
}
window.location.hash = encodeURIComponent(nextDir);
currentPath = nextDir;
});
// Clicking on breadcrumbs
breadcrumbs.on('click', 'a', function(e){
e.preventDefault();
var index = breadcrumbs.find('a').index($(this)),
nextDir = breadcrumbsUrls[index];
breadcrumbsUrls.length = Number(index);
window.location.hash = encodeURIComponent(nextDir);
});
// Navigates to the given hash (path)
function goto(hash) {
hash = decodeURIComponent(hash).slice(1).split('=');
if (hash.length) {
var rendered = '';
// if hash has search in it
if (hash[0] === 'search') {
filemanager.addClass('searching');
rendered = searchData(response, hash[1].toLowerCase());
if (rendered.length) {
currentPath = hash[0];
render(rendered);
}
else {
render(rendered);
}
}
// if hash is some path
else if (hash[0].trim().length) {
rendered = searchByPath(hash[0]);
if (rendered.length) {
currentPath = hash[0];
breadcrumbsUrls = generateBreadcrumbs(hash[0]);
render(rendered);
}
else {
currentPath = hash[0];
breadcrumbsUrls = generateBreadcrumbs(hash[0]);
render(rendered);
}
}
// if there is no hash
else {
currentPath = data.path;
breadcrumbsUrls.push(data.path);
render(searchByPath(data.path));
}
}
}
// Splits a file path and turns it into clickable breadcrumbs
function generateBreadcrumbs(nextDir){
var path = nextDir.split('/').slice(0);
for(var i=1;i<path.length;i++){
path[i] = path[i-1]+ '/' +path[i];
}
return path;
}
// Locates a file by path
function searchByPath(dir) {
var path = dir.split('/'),
demo = response,
flag = 0;
for(var i=0;i<path.length;i++){
for(var j=0;j<demo.length;j++){
if(demo[j].name === path[i]){
flag = 1;
demo = demo[j].items;
break;
}
}
}
demo = flag ? demo : [];
return demo;
}
// Recursively search through the file tree
function searchData(data, searchTerms) {
data.forEach(function(d){
if(d.type === 'folder') {
searchData(d.items,searchTerms);
if(d.name.toLowerCase().match(searchTerms)) {
folders.push(d);
}
}
else if(d.type === 'file') {
if(d.name.toLowerCase().match(searchTerms)) {
files.push(d);
}
}
});
return {folders: folders, files: files};
}
// Render the HTML for the file manager
function render(data) {
var scannedFolders = [],
scannedFiles = [];
if(Array.isArray(data)) {
data.forEach(function (d) {
if (d.type === 'folder') {
scannedFolders.push(d);
}
else if (d.type === 'file') {
scannedFiles.push(d);
}
});
}
else if(typeof data === 'object') {
scannedFolders = data.folders;
scannedFiles = data.files;
}
// Empty the old result and make the new one
fileList.empty().hide();
if(!scannedFolders.length && !scannedFiles.length) {
filemanager.find('.nothingfound').show();
}
else {
filemanager.find('.nothingfound').hide();
}
if(scannedFolders.length) {
scannedFolders.forEach(function(f) {
var itemsLength = f.items.length,
name = escapeHTML(f.name),
icon = '<span class="icon folder"></span>';
if(itemsLength) {
icon = '<span class="icon folder full"></span>';
}
if(itemsLength == 1) {
itemsLength += ' item';
}
else if(itemsLength > 1) {
itemsLength += ' items';
}
else {
itemsLength = 'Empty';
}
var folder = $('<li class="folders">'+icon+'<span class="name">' + name + '</span> <span class="details">' + itemsLength + '</span></li>');
folder.appendTo(fileList);
});
}
if(scannedFiles.length) {
scannedFiles.forEach(function(f) {
var fileSize = bytesToSize(f.size),
name = escapeHTML(f.name),
fileType = name.split('.'),
icon = '<span class="icon file"></span>';
fileType = fileType[fileType.length-1];
icon = '<span class="icon file f-'+fileType+'">.'+fileType+'</span>';
var file = $('<li class="files">'+icon+'<span class="name">'+ name +'</span> <span class="details">'+fileSize+'</span></li>');
file.appendTo(fileList);
});
}
// Generate the breadcrumbs
var url = '';
if(filemanager.hasClass('searching')){
url = '<span>Search results: </span>';
fileList.removeClass('animated');
}
else {
fileList.addClass('animated');
breadcrumbsUrls.forEach(function (u, i) {
var name = u.split('/');
if (i !== breadcrumbsUrls.length - 1) {
url += '<span class="folderName">' + name[name.length-1] + '</span> <span class="arrow">→</span> ';
}
else {
url += '<span class="folderName">' + name[name.length-1] + '</span>';
}
});
}
breadcrumbs.text('').append(url);
// Show the generated elements
fileList.animate({'display':'inline-block'});
}
// This function escapes special html characters in names
function escapeHTML(text) {
return text.replace(/\&/g,'&').replace(/\</g,'<').replace(/\>/g,'>');
}
// Convert file sizes from bytes to human readable units
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Bytes';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
});
});
breadcrumbs = $('.breadcrumbs'),
fileList = filemanager.find('.data');
// Start by fetching the file data from scan.php with an AJAX request
$.get("/phpfiles/scan.php", function(data) {
var response = [data],
currentPath = '',
breadcrumbsUrls = [];
var folders = [],
files = [];
I am having a problem in this line: "/phpfiles/scan.php"
When I put scan.php in the root folder, it works. But when I move it back to phpfiles folder, it won't work.
Sorry for this very noob question.
UPDATE: When I visited the URL: http://localhost/ams/phpfiles/scan.php
It says: No such folder{"name":"files","type":"folder","path":"files/A5","items":[]
So the culprit might be in scan-a5.php:
$dir = "files/A5";
// Run the recursive function
$response = scan($dir);
// This function scans the files folder recursively, and builds a large array
function scan($dir){
$files = array();
// Is there actually such a folder/file?
if(file_exists($dir)){
foreach(scandir($dir) as $f) {
if(!$f || $f[0] == '.') {
continue; // Ignore hidden files
}
if(is_dir($dir . '/' . $f)) {
// The path is a folder
$files[] = array(
"name" => $f,
"type" => "folder",
"path" => $dir . '/' . $f,
"items" => scan($dir . '/' . $f) // Recursively get the contents of the folder
);
}
else {
// It is a file
$files[] = array(
"name" => $f,
"type" => "file",
"path" => $dir . '/' . $f,
"size" => filesize($dir . '/' . $f) // Gets the size of this file
);
}
}
}
else{
echo "No such folder";
}
return $files;
}
// Output the directory listing as JSON
header('Content-type: application/json');
echo json_encode(array(
"name" => "files",
"type" => "folder",
"path" => $dir,
"items" => $response
));

Categories

Resources