Not allowed to load local resource on google chrome - javascript

i a php/jQuery script that list files from remote server. Files can be listed with all subfolders within but my problem is that when want to view file it does not open and through back error on browser console that Not allowed to load local resource: here are the scripts
scan.php
$files = array();
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
);
}
}
}
return $files;
php?>
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('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];
}
});
});
index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>file browser</title>
<!-- Include our stylesheet -->
<link href="assets/css/styles.css" rel="stylesheet"/>
</head>
<body>
</br></br>
<div class="container">
<p align="center"><img src="img/vision.jpg" class="img-thumbnail" alt="Responsive image" height="100" width="350"></p>
</div>
<div class="filemanager">
<div class="search">
<input type="search" placeholder="Find a file.." />
</div>
<div class="breadcrumbs"></div>
<ul class="data"></ul>
<div class="nothingfound">
<div class="nofiles"></div>
<span>No files here.</span>
</div>
</div>
<!--<footer>
</footer>-->
<!-- Include our script files -->
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
In addition if anyone can modify the code and add download button will be thankfull

Related

How Do I add this javascript and HTML code into an angular project? and can i render html from javascript function in angular?

How Do I add this javascript and HTML code into an angular project ?
I have placed the func.js in a src folder in my angular project and in my app.component.ts file
where I tried to import and use ngAfterViewInit() to load and use the javascript functions
These are the javascript and html files I am trying to add to the angular web app:
funcs.js
const uName = 'admin';
const uPass = '12345';
const endpoint = 'http://11.11.111.241:8000';
const resource = {
questionnaire: 'Questionnaire',
valueset: 'ValueSet'
}
//get questionnaire
var url = 'http://cihi.ca/fhir/irrs/Questionnaire/abc-abc-community-on';
var quesJson = getData(resource.questionnaire, '?url=' + url);
quesJson = quesJson.entry[0].resource
// saveJsonToFile(quesJson, 'irrsQuesJson');
var copy = $.extend(true, {}, quesJson);
//convert to lhc form
var lformsQ = LForms.Util.convertFHIRQuestionnaireToLForms(quesJson, 'STU3')
// saveJsonToFile(lformsQ, 'lFormJson');
//prepare valuesets
const vsArray = createValueSetData();
//add value sets
injectValueSet(lformsQ);
// saveJsonToFile(lformsQ, 'lFormValueSetInjected');
// Add the form to the page
var options = { 'prepopulate': true };
LForms.Util.addFormToPage(lformsQ, 'formContainer', options);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
function getData(res, param, log) {
var data = null;
var url = endpoint + '/' + res + param;
$.ajax({
accepts: {
json: 'application/fhir+json',
xml: 'application/fhir+xml'
},
dataType: 'json',
type: 'GET',
url: url,
async: false,
success: function (response) {
data = response;
if (log)
console.log('getData: SUCCESS - "' + url + '"');
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(uName + ":" + uPass));
},
error: function (err) {
if (log)
console.error('getData: FAILED - "' + url + '"')
}
});
return data;
}
//recursively inject valueset into lhc json
function injectValueSet(lhcJson) {
if (lhcJson && 'items' in lhcJson) {
lhcJson.items.forEach(e => {
injectValueSet(e);
});
} else {
if ('answerValueSet' in lhcJson && 'reference' in lhcJson.answerValueSet) {
lhcJson['answers'] = vsArray[lhcJson.answerValueSet.reference];
}
}
}
//save form
function save() {
var quesResp = LForms.Util.getFormFHIRData('QuestionnaireResponse', 'STU3', '#formContainer');
saveJsonToFile(quesResp, 'questionnaireResponse' + '-' + new Date().getTime());
// var newLform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', quesResp, lformsQ, 'STU3');
// LForms.Util.addFormToPage(newLform, 'formContainer2');
}
//open file
function openQues() {
var file = $('#file1')[0].files[0];
const fileReader = new FileReader();
fileReader.onload = event => {
var data = JSON.parse(event.target.result);
var lform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', data, lformsQ, 'STU3');
injectValueSet(lformsQ);
LForms.Util.addFormToPage(lform, 'formContainer');
};
fileReader.onerror = error => console.error("Error loading file!");
fileReader.readAsText(file, "UTF-8");
}
// get valueSet count
function getValueSetCount() {
var count = 0;
var response = getData(resource.valueset, '?_summary=count');
if (response) {
count = response.total;
}
return count;
}
//get all valueSets id
function getValueSetIds() {
var ids = [];
var count = getValueSetCount();
var response = getData(resource.valueset, '?_count=' + count + '&_element=id');
if (response) {
if ('entry' in response && response.entry.length > 0) {
response.entry.forEach(e => {
if ('resource' in e && 'id' in e.resource && 'url' in e.resource) {
ids.push({
'id': e.resource.id,
'url': e.resource.url
});
}
});
}
}
return ids;
}
//create valueSet array for form fields
function createValueSetData() {
var data = {}, dataValueSet, failedIds;
var ids = getValueSetIds();
if (ids) {
failedIds = [];
ids.forEach(idSet => {
var response = getData(resource.valueset, '/' + idSet.id + '/$expand');
if (response && 'expansion' in response
&& 'contains' in response.expansion
&& response.expansion.contains.length > 0) {
dataValueSet = [];
response.expansion.contains.forEach(e => {
dataValueSet.push({
'text': e.code + ' - ' + e.display,
'code': e.code
});
});
data[idSet.url] = dataValueSet;
} else {
failedIds.push(idSet.id);
}
});
if (failedIds.length > 0) {
console.error("Failed fetching valueSets for the following IDs: \n Count: "
+ failedIds.length + "\n" + failedIds);
}
}
return data;
}
//save json to file
function saveJsonToFile(json, fileName) {
var textToSave = JSON.stringify(json);
var data = new Blob([textToSave], { type: 'text/plain' });
var textFileURL = window.URL.createObjectURL(data);
var hiddenElement = document.createElement('a');
hiddenElement.href = textFileURL;
hiddenElement.target = '_blank';
hiddenElement.download = fileName + '.txt';
hiddenElement.click();
}
**Html file :**
<!DOCTYPE html>
<html>
<head>
<link href="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/styles/lforms.min.css" media="screen"
rel="stylesheet" />
<link href="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.css"
rel="stylesheet" />
</head>
<body>
<button onclick="save()">
Save QuestionnaireResponse
</button>
<input type="file" id="file1">
<button onclick="openQues()">
Open QuestionnaireResponse
</button>
<div id="formContainer"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/lforms.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/fhir/STU3/lformsFHIR.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
first create a new component through angular cli and add the variable declarations in .ts file i.e
const uName = 'admin';
const uPass = '12345';
const endpoint = 'http://11.11.111.241:8000';
const resource = {
questionnaire: 'Questionnaire',
valueset: 'ValueSet'
}
//get questionnaire
var url = 'http://cihi.ca/fhir/irrs/Questionnaire/abc-abc-community-on';
var quesJson = getData(resource.questionnaire, '?url=' + url);
quesJson = quesJson.entry[0].resource
// saveJsonToFile(quesJson, 'irrsQuesJson');
var copy = $.extend(true, {}, quesJson);
//convert to lhc form
var lformsQ = LForms.Util.convertFHIRQuestionnaireToLForms(quesJson, 'STU3')
// saveJsonToFile(lformsQ, 'lFormJson');
//prepare valuesets
const vsArray = createValueSetData();
//add value sets
injectValueSet(lformsQ);
// saveJsonToFile(lformsQ, 'lFormValueSetInjected');
// Add the form to the page
var options = { 'prepopulate': true };
LForms.Util.addFormToPage(lformsQ, 'formContainer', options);
then in .html page add the html code
<button onclick="save()">
Save QuestionnaireResponse
</button>
<input type="file" id="file1">
<button onclick="openQues()">
Open QuestionnaireResponse
</button>
<div id="formContainer"></div>
and then add the functions inside tag in the html file
function getData(res, param, log) {
var data = null;
var url = endpoint + '/' + res + param;
$.ajax({
accepts: {
json: 'application/fhir+json',
xml: 'application/fhir+xml'
},
dataType: 'json',
type: 'GET',
url: url,
async: false,
success: function (response) {
data = response;
if (log)
console.log('getData: SUCCESS - "' + url + '"');
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(uName + ":" + uPass));
},
error: function (err) {
if (log)
console.error('getData: FAILED - "' + url + '"')
}
});
return data;
}
//recursively inject valueset into lhc json
function injectValueSet(lhcJson) {
if (lhcJson && 'items' in lhcJson) {
lhcJson.items.forEach(e => {
injectValueSet(e);
});
} else {
if ('answerValueSet' in lhcJson && 'reference' in lhcJson.answerValueSet) {
lhcJson['answers'] = vsArray[lhcJson.answerValueSet.reference];
}
}
}
//save form
function save() {
var quesResp = LForms.Util.getFormFHIRData('QuestionnaireResponse', 'STU3', '#formContainer');
saveJsonToFile(quesResp, 'questionnaireResponse' + '-' + new Date().getTime());
// var newLform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', quesResp, lformsQ, 'STU3');
// LForms.Util.addFormToPage(newLform, 'formContainer2');
}
//open file
function openQues() {
var file = $('#file1')[0].files[0];
const fileReader = new FileReader();
fileReader.onload = event => {
var data = JSON.parse(event.target.result);
var lform = LForms.Util.mergeFHIRDataIntoLForms('QuestionnaireResponse', data, lformsQ, 'STU3');
injectValueSet(lformsQ);
LForms.Util.addFormToPage(lform, 'formContainer');
};
fileReader.onerror = error => console.error("Error loading file!");
fileReader.readAsText(file, "UTF-8");
}
// get valueSet count
function getValueSetCount() {
var count = 0;
var response = getData(resource.valueset, '?_summary=count');
if (response) {
count = response.total;
}
return count;
}
//get all valueSets id
function getValueSetIds() {
var ids = [];
var count = getValueSetCount();
var response = getData(resource.valueset, '?_count=' + count + '&_element=id');
if (response) {
if ('entry' in response && response.entry.length > 0) {
response.entry.forEach(e => {
if ('resource' in e && 'id' in e.resource && 'url' in e.resource) {
ids.push({
'id': e.resource.id,
'url': e.resource.url
});
}
});
}
}
return ids;
}
//create valueSet array for form fields
function createValueSetData() {
var data = {}, dataValueSet, failedIds;
var ids = getValueSetIds();
if (ids) {
failedIds = [];
ids.forEach(idSet => {
var response = getData(resource.valueset, '/' + idSet.id + '/$expand');
if (response && 'expansion' in response
&& 'contains' in response.expansion
&& response.expansion.contains.length > 0) {
dataValueSet = [];
response.expansion.contains.forEach(e => {
dataValueSet.push({
'text': e.code + ' - ' + e.display,
'code': e.code
});
});
data[idSet.url] = dataValueSet;
} else {
failedIds.push(idSet.id);
}
});
if (failedIds.length > 0) {
console.error("Failed fetching valueSets for the following IDs: \n Count: "
+ failedIds.length + "\n" + failedIds);
}
}
return data;
}
//save json to file
function saveJsonToFile(json, fileName) {
var textToSave = JSON.stringify(json);
var data = new Blob([textToSave], { type: 'text/plain' });
var textFileURL = window.URL.createObjectURL(data);
var hiddenElement = document.createElement('a');
hiddenElement.href = textFileURL;
hiddenElement.target = '_blank';
hiddenElement.download = fileName + '.txt';
hiddenElement.click();
}
and importantly add all the script imports to index.html the main index which is outside the app folder
add this in head section -
<link href="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/styles/lforms.min.css" media="screen"
rel="stylesheet" />
<link href="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.css"
rel="stylesheet" />
as well as this -
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/lforms.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/lforms-versions/17.3.2/fhir/STU3/lformsFHIR.min.js"></script>
<script src="https://clinicaltables.nlm.nih.gov/autocomplete-lhc-versions/17.0.3/autocomplete-lhc.min.js"></script>
<script src="./index.js"></script>
last but not least add the selector of the created component in the app.component.html file
it should look something like this in created component of .html file add this to app.component.html
import { Component, OnInit } from '#angular/core';
import * as $ from 'jquery';
import {OpenQues,save} from '../assets/scripts.js'
declare var tesing: any;
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Look jQuery Animation working in action!';
public ngOnInit()
{
$.getScript('./assets/scripts.js');
}
public open()
{
OpenQues();
}
public save()
{
save();
}
}
This worked for me

f[i].insertionPoints[0].rectangles.add({geometricBounds:

i´m desperately finding a solution for my issue. I need to place a huge amount of inline graphics in InDesign with this script, but for some reason it doesn't work. I have a very poor knowledge of Javascript and my time is running out so i cannot spend much time studying JS. I'm working in InDesign CC2014 on an iMac with Yosemite.
The following error message pops-up:
error snap:
I'll be so glad if someone give me a light on this.
main();
function main() {
var name, f, file, text,
arr = [];
if(app.documents.length != 0) {
var doc = app.activeDocument;
var folder = Folder.selectDialog("Choose a folder with images");
if (folder != null) {
app.findObjectPreferences = app.changeGrepPreferences = NothingEnum.NOTHING;
app.findGrepPreferences.findWhat = "#.+?#";
f = doc.findGrep(true);
for (i = 0; i < f.length; i++) {
name = f[i].contents.replace(/#/g, "");
file = new File(folder.fsName + "/" + name);
if (file.exists) {
f[i].contents = "";
var rect = f[i].insertionPoints[0].rectangles.add({geometricBounds:[0,0, 60, 40.667 ]} );
rect.place ( file );
rect.fit ( FitOptions.FRAME_TO_CONTENT);
}
else {
arr.push("File doesn't exist '" + name + "'");
}
}
app.findObjectPreferences = app.changeGrepPreferences = NothingEnum.NOTHING;
arr.push("------------------------------------------");
text = arr.join("\r");
writeToFile(text);
}
}
else{
alert("Please open a document and try again.");
}
}
function writeToFile(text) {
var file = new File("~/Desktop/Place inline images.txt");
if (file.exists) {
file.open("e");
file.seek(0, 2);
}
else {
file.open("w");
}
file.write(text + "\r");
file.close();
}
Problem is - probably - cause script is editing found contents and refering to it in the next lines of code.
I suggest to use backward looping and move f[i].contents = "" to the line after.
Something like:
main();
function main() {
var name, f, cF, file, text,
arr = [];
if(app.documents.length != 0) {
var doc = app.activeDocument;
var folder = Folder.selectDialog("Choose a folder with images");
if (folder != null) {
app.findObjectPreferences = app.changeGrepPreferences = NothingEnum.NOTHING;
app.findGrepPreferences.findWhat = "#.+?#";
f = doc.findGrep(true);
while(cF = f.pop()) {
name = cF.contents.replace(/#/g, "");
file = new File(folder.fsName + "/" + name);
if (file.exists) {
var rect = cF.insertionPoints[0].rectangles.add({geometricBounds:[0,0, 60, 40.667 ]} );
rect.place ( file );
rect.fit ( FitOptions.FRAME_TO_CONTENT);
cF.contents = "";
}
else {
arr.push("File doesn't exist '" + name + "'");
}
}
app.findObjectPreferences = app.changeGrepPreferences = NothingEnum.NOTHING;
arr.push("------------------------------------------");
text = arr.join("\r");
writeToFile(text);
}
}
else{
alert("Please open a document and try again.");
}
}
function writeToFile(text) {
var file = new File("~/Desktop/Place inline images.txt");
if (file.exists) {
file.open("e");
file.seek(0, 2);
}
else {
file.open("w");
}
file.write(text + "\r");
file.close();
}

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?

AJAX Upload Web App

I need some assistance please.
I am trying to create an ajax upload web app from scratch as a personal hobby.
I was able to get the files to upload to my uploads folder successfully, but I just can't seem to get the uploaded links to appear under the upload box and stay there permanently even after refreshing the web page.
I keep getting this error message in the google chrome browser console: Uncaught TypeError: Cannot read property 'length' of undefinedand it is pointing me to this line in the index.php:for(x = 0; x < data.succeeded.length; x = x + 1) {
Also the google chrome console is marking this as (anonymous function) in the upload.js file:o.options.finished(uploaded);
I had used some youtube videos as a guide, but I just can't seem to figure it out.
Kindly Help Me Please
This is the index.php code and below is the upload.php code also the upload.js code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Uploader</title>
<link rel="stylesheet" href="css/global.css">
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Upload files</legend>
<input type="file" id="file" name="file[]" required multiple>
<input type="submit" id="submit" name="submit" value="Upload">
</fieldset>
<div class="bar">
<span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt"></span></span>
</div>
<div id="uploads" class="uploads">
Uploaded file links will appear here.
</div>
<script src="js/upload.js"></script>
<script>
document.getElementById('submit').addEventListener('click', function(e) {
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'upload.php',
finished: function(data) {
var uploads = document.getElementById('uploads'),
succeeded = document.createElement('div'),
failed = document.createElement('div'),
anchor,
span,
x;
if(data.failed.length) {
failed.innerHTML = '<p>Unfortunately, the following failed:</p>';
}
uploads.innerText = '';
for(x = 0; x < data.succeeded.length; x = x + 1) {
anchor = document.createElement('a');
anchor.href = 'uploads/' + data.succeeded[x].file;
anchor.innerText = data.succeeded[x].name;
anchor.target = '_blank';
succeeded.appendChild(anchor);
}
for(x = 0; x < data.failed.length; x = x + 1 ) {
span = document.createElement('span');
span.innerText = data.failed[x].name;
failed.appendChild(span);
}
uploads.appendChild(succeeded);
upload.appendChild(failed);
},
error: function() {
console.log('Not working');
}
});
});
</script>
</form>
</body>
</html>
Upload.php code
<?php
header('Content-Type: application/json');
$uploaded = '';
$allowed = '';
$succedeed = '';
$failed = '';
if(!empty($_FILES['file'])) {
foreach($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key] === 0) {
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if(move_uploaded_file($temp, "uploads/{$file}") === true) {
$succedeed[] = array(
'name' => $name,
'file' => $file
);
} else {
$failed[] = array(
'name' => $name
);
}
}
}
if(!empty($_POST['ajax'])) {
echo json_encode(array(
'succedeed' => $succedeed,
'failed' => $failed
));
}
}
This is the upload.js code
var app = app || {};
(function(o) {
"use strict";
//Private methods
var ajax, getFormData, setProgress;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if(this.readyState === 4) {
if(this.status === 200) {
uploaded = JSON.parse(this.response);
if(typeof o.options.finished === 'function') {
o.options.finished(uploaded);
}
} else {
if(typeof o.options.error === 'function') {
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(event) {
var percent;
if(event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData(), i;
for(i = 0; i < source.length; i = i + 1) {
data.append('file[]', source[i]);
}
data.append('ajax', true);
return data;
};
setProgress = function(value) {
if(o.options.progressBar !== undefined) {
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined) {
o.options.progressText.innerText = value ? value + '%' : '';
}
};
o.uploader = function(options) {
o.options = options;
if(o.options.files !== undefined) {
ajax(getFormData(o.options.files.files));
}
}
}(app));
I think the problem is due to if(move_uploaded_file($temp, "uploads/{$file}") === true) try if(move_uploaded_file($temp, "uploads/{$file}") == true)
and also check data.succedeed spell in index.php

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