html file cannot find uploads directory - javascript

I have an html file that is supposed to display every picture in the uploads directory, however it does not recognize an uploads directory. I am using a nodejs server. Here is my html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>gummy bear</title>
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link href="css/styles.css" rel="stylesheet">
</head>
<body>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
var dir = "/uploads/";
var fileextension = ".jpg";
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='" + dir + filename + "'>");
});
}
});
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>
and here is what my directory layout looks like:
app.js css index.html javascripts LICENSE node_modules package.json README.md upload.html uploads
and inside of uploads is:
➜ uploads ls
1.jpg
Thanks in advance!

Looking through the sample code it seems like the HTML file expects some HTML to be returned from http://localhost:3000/uploads.
The questions is why does the /uploads endpoint not return anything but instead returns a 404 response?
The answer to this would lie in the main executable Javascript file in the node.js application. Likely a file called server.js or index.js.
Here is an example of how you would go about creating the correct node.js application for you HTML file to work:
server.js
app.all('/uploads', function (req, res) {
var folder = './public/uploads',
html = '<html><body>##files##</body></html>';
fs.readdir(folder, (err, files) => {
var fileHrefs = '';
files.forEach(function (file) {
fileHrefs += '' + file + '';
});
html = html.replace('##files##', fileHrefs);
res.send(err || html);
})
});
This snippet of code iterates over all files in the uploads directory and wraps them in an a tag which is then returned by the server.
index.html
To make your index HTML file work a couple small changes need to be made:
change $(data).find() to $(data).filter()
remove the directory from the image source. change <img src='" + dir + filename + "'> to <img src='" + filename + "'>
Complete working sample
You can also find the whole working sample here: https://github.com/kohlikohl/list-images-in-dir

Related

How to add a Javascript file to HTML while running on nodejs

I create simple nodeJs server this is my server.js file:
var http = require('http');
var fs = require('fs');
var path = require('path');
var server = http.createServer(function(req, resp){
// Print the name of the file for which request is made.
console.log("Request for demo file received.");
fs.readFile("www/index.html",function(error, data){
var filePath = '.' + req.url;
var extname = path.extname(filePath);
var contentType = 'text/html';
if(extname == '.js'){
contentType = 'text/javascript';
console.log("extname is .js")
}
resp.writeHead(200, { 'Content-Type': contentType });
resp.end(data, 'utf-8');
});
});
server.listen(8081, '127.0.0.1');
this is my HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Professor Test DApp</title>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
<link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet' type='text/css'>
</head>
<body class="container">
<h1>A Simple Test Professor DApp</h1>
<div class="table-responsive">
</div>
Apply
</body>
<script src="https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script type="text/javascript" src="index112.js"></script>
</html>
and this is my js file:
function apply(){
console.log("apply in js file called")
}
when I open it in the browser without a server it works fine but when I run it in server the js file cannot be detected.
I think you need to serve static files. create public folder and move index112.js in public folder. use the express.static built-in middleware function as per the following.
app.use(express.static(path.join(__dirname, 'public')));
Please check your index112.js file path because while running on server there might be possiblity that server is not able to find the file try giving absolute or relative path of the file in src attribute this might help.
Absolute or Relative Path Info

Getting 404 error when trying to access local files

I am trying to make a very simple html with local server that displays all images in a local directory (content folder). But I am getting jquery-3.2.1.min.js:4 GET http://localhost:8080/content/ 404 (Not Found)
So, my file structure looks like:
rootfolder
-content/
-js/
-index.html
-server.js
server.js looks like this:
var connect = require('connect')
var serveStatic = require('serve-static')
connect().use(serveStatic(__dirname)).listen(8080, function () {
console.log('Server running on 8080...')
console.log('dirname', __dirname)
})
index.html like this:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.2.1.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div id="img-container">
</div>
</body>
</html>
index.js looks like this:
window.onload = function () {
var folder = 'content/'
$.ajax({
url: folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if (val.match(/\.(jpe?g|png|gif)$/)) {
$("body").append( "<img src='"+ folder + val +"'>" )
}
})
}
})
console.log('test2')
}
The code isn't very clean at the moment but I want to figure out why I am getting 404 Not Found error first.

Cordova File Opener Failing to Find File

I'm trying to use cordova-plugin-file-opener2 to load a pdf in Cordova. I can't seem to get it to work in the browser or on Android.
Here is my app.js file:
(function () {
document.querySelector('#file-button').addEventListener('click', openFile);
function openFile(){
console.log('opening file');
console.log(cordova.file.applicationDirectory);
var fileName = 'www/assets/pdf/foo.pdf';
var pathToFile = cordova.file.applicationDirectory + fileName;
window.resolveLocalFileSystemURL(pathToFile, function (entry) {
cordova.plugins.fileOpener2.open(
entry.toInternalURL(),
'application/pdf', {
error: function (e) {
alert.log('Error status: ' + e.status + ' - Error message: ' + e.message);
},
success: function () {
alert.log('file opened successfully');
}
}
);
}, function (e) {
alert('File Not Found');
});
}
}());
And here's the html:
<!DOCTYPE html>
<html>
<head>
<script src="cordova.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
</head>
<body>
<p><button id="file-button" class="help-btn">Help</button></p>
<div class='header'><h1>Directory</h1></div>
<div class='search-view'>
<input class='search-key' type="search" placeholder="Enter name"/>
<ul class='list employee-list'></ul>
</div>
<script src="lib/jquery.js"></script>
<script src="js/services/memory/EmployeeService.js"></script>
<script src="js/app.js"></script>
</body>
</html>
When the 'file-button' is clicked, it triggers the openFile function.
This shows me the following in the console:
adding proxy for Device cordova.js:1010:9
adding proxy for File cordova.js:1010:9
opening file app.js:6:9
"http://localhost:8000/" app.js:7:9
And the alert message says 'File not found'.
App.js is located in www --> js
foo.pdf is located in www --> assets --> pdf

Accessing Functions From Other JS Files - DOJO

Im trying to call a function from another js file that is located in the same application directory as my main js script and html file. I receive an error claiming that the referenced function does not exist. I have referenced both of the scripts in the main html file in the proper order but cant for the life of me figure out why it cannot detect the function. I can only assume it has something to do with how dojo parses through the files and have experimented with both its dojo/domReady! and dojo/ready modules in hopes to force scripts to load. I feel like this should be much simpler than Im making it out to be. Any help would be greatly appreciated.
html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Asset View</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://js.arcgis.com/3.14/dijit/themes/claro/claro.css">
<link rel="stylesheet" href="http://js.arcgis.com/3.14/esri/css/esri.css">
<link rel="stylesheet" href= "styles/styles.css">
<script src="http://js.arcgis.com/3.14/"></script>
<script src="scripts/requests-js.js"></script>
<script src="scripts/layout-js.js"></script>
<script src="scripts/xmain-js.js"></script>
</head>
<body class = "claro">
</body>
</html>
requests-js.js
require(["dojo/dom","dojo/on","dojo/request","dojo/json","dojo/parser","dojo/ready"
], function(dom,on,request,JSON,parser,ready) {
ready(function() {
console.log("request start");
function sendRequest (url,assetCode,fromDate,toDate) {
console.log("Request innit");
request(url,{
method: "POST",
handleAs: "json",
headers: {"Content-Type": "application/json"},
data: JSON.stringify(
[
{
"AssetCodes": assetCode,
"FromGasDay": fromDate,
"ToGasDate": toDate
}
]
)
}).then(function(resp){
console.log(JSON.stringify(resp));
var naStorageJSON = resp;
});
}
console.log("request end");
});
});
main-js.js
require([
"dojo/dom","dojo/on","dojo/parser","dojo/json","dojo/request","dojo/ready"
], function(dom,on,parser,JSON,request,ready) {
ready(function() {
console.log("Main Start");
var url = "http://*********";
var assetCode = ["**"];
var toDate = "****";
var fromDate ="*****";
on(dom.byId("senecaLakeBtn"),"click", sendRequest(url,assetCode,toDate,fromDate));
console.log("Main End");
});
});
The issue is scope here. By declaring an empty array at the top of the js script (outside of its successive functions) the function can be accessible to other scripts in the application.
var app = [];
require(["dojo/dom","dojo/on","dojo/request","dojo/json","dojo/parser","dojo/ready"
], function(dom,on,request,JSON,parser,ready) {
ready(function(){
app.sendRequest = function sendRequest (url,assetCode,fromDate,toDate) {
...
...
}
}
it can them be called upon from other scripts by referencing
app.sendRequest(arg1,arg2,arg3);

How to download external file using phonegap?

I am trying to download an apk file on a button click using phonegap. Why does this code not work? Nothing happens when I click Download. Could someone point me in the right direction? Thanks.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script charset="utf-8" src = "jquery-1.10.1.min.js"></script>
<script charset="utf-8" src = "cordova-2.7.0.js"></script>
<script>
function foo()
{
var fileTransfer = new FileTransfer();
fileTransfer.download(
"http://samplewebsite.com/example.apk",
"file:///sdcard/example.apk",
function(entry) {
console.log("download complete: " + entry.fullPath);
},
function(error) {
console.log("download error source " + error.source);
console.log("download error target " + error.target);
console.log("upload error code" + error.code);
}
);
}
</script>
</head>
<body>
<button onclick="foo()">Download</button>
</body>
</html>
var fileTransfer = new FileTransfer();
var uri = encodeURI(url);
var filePath= "/sdcard/directory/file.extension";
fileTransfer.download(uri,filePath,
function(entry) {
//success
},
function(error) {
//failed
}
);
This worked for me
Your code works fine.
This seems stupid but have you tried to use alert() instead of console.log() in the callbacks?
If you are sure the callback code is not invoked try to run just the app created by the phonegap' create script and check that the device is ready before doing other tests.
just my 2c

Categories

Resources