Rectangle 27 11

Mutable paths (test/staging/production domains) is always a problem in javascript, the best option is to include the root path of your application/website in the HTML. The obvious place to do this is in your template layer. For example:

<body data-root="${rootContext}">
<!-- or whatever syntax your template layer uses -->

And grab it with javascript for usage in your scripts.

var rootContext = document.body.getAttribute("data-root");

Note, you can only do this when the DOM is ready (or when document.body is available, differs cross browser) ;)

<script>
    var rootContext = ${rootContext} // or whatever syntax your template layer uses.
</script>

At least with the 'data-root' technique, you can store the value wherever you like and avoid a global definition.

So in your code where you reference an image, you can do the following:

img.src = rootContext + "/media/js/close.gif";

Or create a nice helper method:

// lets use a namespace to avoid globals.
 var myApp = {
     // still need to set this when DOM/body is ready
     rootContext: document.body.getAttribute("data-root"),
     getContext: function( src ) {
         return this.rootContext + src;
     }
 }

img.src = myApp.getContext( "/media/js/close.gif" );

In the helper method, you can also write some code to ensure proper uses of / and whatnot.

Why not just use <base>?

html - Relative paths of images in JavaScript - Stack Overflow

javascript html path
Rectangle 27 16

ES6: Only one line in Vanila JS (it return null if don't find instead of giving error):

'path.string'.split('.').reduce((p,c)=>p&&p[c]||null, MyOBJ)
'a.b.c'.split('.').reduce((p,c)=>p&&p[c]||null, {a:{b:{c:1}}})

For a ready to use function that also recognizes false, 0 and negative number and accept default values as parameter:

resolvePath(window,'document.body') => <body>
resolvePath(window,'document.body.xyz') => undefined
resolvePath(window,'document.body.xyz', null) => null
resolvePath(window,'document.body.xyz', 1) => 1

To set a path (Requested by @rob-gordon) you can use:

const setPath = (object, path, value) => path
   .split('.')
   .reduce((o,p) => o[p] = path.split('.').pop() === p ? value : o[p] || {}, object)
let myVar = {}
setPath(myVar, 'a.b.c', 42) => 42
console.log(myVar) => {a: {b: {c: 42}}}
const resolvePath = (object, path, defaultValue) => path
   .split(/[\.\[\]\'\"]/)
   .filter(p => p)
   .reduce((o, p) => o ? o[p] : defaultValue, object)
const myVar = {a:{b:[{c:1}]}}
resolvePath(myVar,'a.b[0].c') => 1
resolvePath(myVar,'a["b"][\'0\'].c') => 1
let o = {a:{b:{c:1}}}; let str = 'a.b.c'; str.split('.').splice(0, str.split('.').length - 1).reduce((p,c)=>p&&p[c]||null, o)[str.split('.').slice(-1)] = "some new value";

I like the idea of using reduce but your logic seems off for 0, undefined and null values. {a:{b:{c:0}}} returns null instead of 0. Perhaps explicitly checking for null or undefined will clear up these issues. (p,c)=>p === undefined || p === null ? undefined : p[c]

Hi @SmujMaiku, the "ready to use" function return correctly for '0', 'undefined' and 'null', I just tested on the console: resolvePath({a:{b:{c:0}}},'a.b.c',null) => 0; It check if the key exists instead of the value itself which avoid more than one check

jquery - Accessing nested JavaScript objects with string key - Stack O...

javascript jquery path nested
Rectangle 27 16

ES6: Only one line in Vanila JS (it return null if don't find instead of giving error):

'path.string'.split('.').reduce((p,c)=>p&&p[c]||null, MyOBJ)
'a.b.c'.split('.').reduce((p,c)=>p&&p[c]||null, {a:{b:{c:1}}})

For a ready to use function that also recognizes false, 0 and negative number and accept default values as parameter:

resolvePath(window,'document.body') => <body>
resolvePath(window,'document.body.xyz') => undefined
resolvePath(window,'document.body.xyz', null) => null
resolvePath(window,'document.body.xyz', 1) => 1

To set a path (Requested by @rob-gordon) you can use:

const setPath = (object, path, value) => path
   .split('.')
   .reduce((o,p) => o[p] = path.split('.').pop() === p ? value : o[p] || {}, object)
let myVar = {}
setPath(myVar, 'a.b.c', 42) => 42
console.log(myVar) => {a: {b: {c: 42}}}
const resolvePath = (object, path, defaultValue) => path
   .split(/[\.\[\]\'\"]/)
   .filter(p => p)
   .reduce((o, p) => o ? o[p] : defaultValue, object)
const myVar = {a:{b:[{c:1}]}}
resolvePath(myVar,'a.b[0].c') => 1
resolvePath(myVar,'a["b"][\'0\'].c') => 1
let o = {a:{b:{c:1}}}; let str = 'a.b.c'; str.split('.').splice(0, str.split('.').length - 1).reduce((p,c)=>p&&p[c]||null, o)[str.split('.').slice(-1)] = "some new value";

I like the idea of using reduce but your logic seems off for 0, undefined and null values. {a:{b:{c:0}}} returns null instead of 0. Perhaps explicitly checking for null or undefined will clear up these issues. (p,c)=>p === undefined || p === null ? undefined : p[c]

Hi @SmujMaiku, the "ready to use" function return correctly for '0', 'undefined' and 'null', I just tested on the console: resolvePath({a:{b:{c:0}}},'a.b.c',null) => 0; It check if the key exists instead of the value itself which avoid more than one check

jquery - Accessing nested JavaScript objects with string key - Stack O...

javascript jquery path nested
Rectangle 27 1

I already tried this. Give error $.cookie is not a function.

javascript - setting cookies using Jquery - Stack Overflow

javascript jquery servlets cookies path
Rectangle 27 2

If you have the image name in your data object and the image is in your Content folder, you can use Url.Content() to get the path to it, as showed here. So your template could be like:

Content/Images/image.jpg

But if you have only the id and need to generate the image as a http response, you can create an action method for that, as showed here. So your template would be:

.Template("<span><img src='" + Url.Action("GetImage", "Search") + "/${data.ImageId}' " +
"width='20' height='20' />&nbsp;${data.Name}</span>")
Search/GetImage/1

In both cases you somehow concat the Javascript variable in an ASP.Net string, as showed in this answer of a friend of mine.

javascript - Kendo autocomplete template img src from database - Stack...

javascript asp.net-mvc kendo-ui autocomplete kendo-template
Rectangle 27 95

var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function (request, response) {
    console.log('request starting...');

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';

    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
        case '.json':
            contentType = 'application/json';
            break;
        case '.png':
            contentType = 'image/png';
            break;      
        case '.jpg':
            contentType = 'image/jpg';
            break;
        case '.wav':
            contentType = 'audio/wav';
            break;
    }

    fs.readFile(filePath, function(error, content) {
        if (error) {
            if(error.code == 'ENOENT'){
                fs.readFile('./404.html', function(error, content) {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                });
            }
            else {
                response.writeHead(500);
                response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
                response.end(); 
            }
        }
        else {
            response.writeHead(200, { 'Content-Type': contentType });
            response.end(content, 'utf-8');
        }
    });

}).listen(8125);
console.log('Server running at http://127.0.0.1:8125/');

UPDATE If you need to access your server from external demand/file, you need to overcome the CORS, in your node.js file by writing the below, as I mentioned in a previous answer here

// Website you wish to allow to connect
response.setHeader('Access-Control-Allow-Origin', '*');

// Request methods you wish to allow
response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

// Request headers you wish to allow
response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
response.setHeader('Access-Control-Allow-Credentials', true);

As Adrian mentioned, in the comments, he wrote an ES6 code with full explanation here, I just re-posting his code below, in case the code gone from the original site for any reason:

const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const port = process.argv[2] || 9000;

http.createServer(function (req, res) {
  console.log(`${req.method} ${req.url}`);

  // parse URL
  const parsedUrl = url.parse(req.url);
  // extract URL path
  let pathname = `.${parsedUrl.pathname}`;
  // based on the URL path, extract the file extention. e.g. .js, .doc, ...
  const ext = path.parse(pathname).ext;
  // maps file extention to MIME typere
  const map = {
    '.ico': 'image/x-icon',
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.json': 'application/json',
    '.css': 'text/css',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.wav': 'audio/wav',
    '.mp3': 'audio/mpeg',
    '.svg': 'image/svg+xml',
    '.pdf': 'application/pdf',
    '.doc': 'application/msword'
  };

  fs.exists(pathname, function (exist) {
    if(!exist) {
      // if the file is not found, return 404
      res.statusCode = 404;
      res.end(`File ${pathname} not found!`);
      return;
    }

    // if is a directory search for index file matching the extention
    if (fs.statSync(pathname).isDirectory()) pathname += '/index' + ext;

    // read file from file system
    fs.readFile(pathname, function(err, data){
      if(err){
        res.statusCode = 500;
        res.end(`Error getting the file: ${err}.`);
      } else {
        // if the file is found, set Content-type and send data
        res.setHeader('Content-type', map[ext] || 'text/plain' );
        res.end(data);
      }
    });
  });


}).listen(parseInt(port));

console.log(`Server listening on port ${port}`);
response.writeHead(200
response.writeHead(404

Would that code not allow going up the file tree by doing something like 127.0.0.1/../../../etc/passwd ? I see no checks against that.

@Adrian This code is very awesome, but I have found a way to get root access with it. The solution is to limit the amount of leading periods on the filename to one so you can't do ../../etc/password stuff. gist.github.com/amejiarosario/53afae82e18db30dadc9bc39035778e5

Node.js quick file server (static files over HTTP) - Stack Overflow

node.js http fileserver
Rectangle 27 94

var http = require('http');
var fs = require('fs');
var path = require('path');

http.createServer(function (request, response) {
    console.log('request starting...');

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';

    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
        case '.json':
            contentType = 'application/json';
            break;
        case '.png':
            contentType = 'image/png';
            break;      
        case '.jpg':
            contentType = 'image/jpg';
            break;
        case '.wav':
            contentType = 'audio/wav';
            break;
    }

    fs.readFile(filePath, function(error, content) {
        if (error) {
            if(error.code == 'ENOENT'){
                fs.readFile('./404.html', function(error, content) {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                });
            }
            else {
                response.writeHead(500);
                response.end('Sorry, check with the site admin for error: '+error.code+' ..\n');
                response.end(); 
            }
        }
        else {
            response.writeHead(200, { 'Content-Type': contentType });
            response.end(content, 'utf-8');
        }
    });

}).listen(8125);
console.log('Server running at http://127.0.0.1:8125/');

UPDATE If you need to access your server from external demand/file, you need to overcome the CORS, in your node.js file by writing the below, as I mentioned in a previous answer here

// Website you wish to allow to connect
response.setHeader('Access-Control-Allow-Origin', '*');

// Request methods you wish to allow
response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

// Request headers you wish to allow
response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
response.setHeader('Access-Control-Allow-Credentials', true);

As Adrian mentioned, in the comments, he wrote an ES6 code with full explanation here, I just re-posting his code below, in case the code gone from the original site for any reason:

const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const port = process.argv[2] || 9000;

http.createServer(function (req, res) {
  console.log(`${req.method} ${req.url}`);

  // parse URL
  const parsedUrl = url.parse(req.url);
  // extract URL path
  let pathname = `.${parsedUrl.pathname}`;
  // based on the URL path, extract the file extention. e.g. .js, .doc, ...
  const ext = path.parse(pathname).ext;
  // maps file extention to MIME typere
  const map = {
    '.ico': 'image/x-icon',
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.json': 'application/json',
    '.css': 'text/css',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.wav': 'audio/wav',
    '.mp3': 'audio/mpeg',
    '.svg': 'image/svg+xml',
    '.pdf': 'application/pdf',
    '.doc': 'application/msword'
  };

  fs.exists(pathname, function (exist) {
    if(!exist) {
      // if the file is not found, return 404
      res.statusCode = 404;
      res.end(`File ${pathname} not found!`);
      return;
    }

    // if is a directory search for index file matching the extention
    if (fs.statSync(pathname).isDirectory()) pathname += '/index' + ext;

    // read file from file system
    fs.readFile(pathname, function(err, data){
      if(err){
        res.statusCode = 500;
        res.end(`Error getting the file: ${err}.`);
      } else {
        // if the file is found, set Content-type and send data
        res.setHeader('Content-type', map[ext] || 'text/plain' );
        res.end(data);
      }
    });
  });


}).listen(parseInt(port));

console.log(`Server listening on port ${port}`);
response.writeHead(200
response.writeHead(404

Would that code not allow going up the file tree by doing something like 127.0.0.1/../../../etc/passwd ? I see no checks against that.

@Adrian This code is very awesome, but I have found a way to get root access with it. The solution is to limit the amount of leading periods on the filename to one so you can't do ../../etc/password stuff. gist.github.com/amejiarosario/53afae82e18db30dadc9bc39035778e5

Node.js quick file server (static files over HTTP) - Stack Overflow

node.js http fileserver
Rectangle 27 1

I just tried npm info which isn't a thing evidently, because I got all errors. But the first line was my OS version, second was PATH to node.exe and PATH to npm-cli.js, third was node version, fourth was npm version. Then invalid package.json, etc, etc I'm sure there's a right way, but I think it showed me everything you are hoping to see... Forgive me for suggesting bad answer. Maybe just check your npm-debug.log Perhaps you can find answers to your questions there.

** EDIT I found something in npm help

npm config list

npm config list gave me the node bin location, and also led me to npm config ls -l which contained a node-version string. As it turns out, npm is using an absolute path to /usr/bin/nodejs. The latest version of node is installed to /usr/local/bin/node with a symlink to /usr/local/bin/nodejs, but npm seems happy to ignore my $PATH variable entirely. Now I just need to find a way to point npm to the proper directory and I'm set.

javascript - How do I list Node.js version and path currently being us...

javascript node.js bash ubuntu
Rectangle 27 4

When dealing with relative paths you might need to include a "." at the beginning of the path string (to specify that you want to go from the current path). I ran into this issue recently while testing out r.js on grunt. I had set my baseUrl to "/" initially when it should've been "."

It's a little weird since the error message I got seemed to have the correct base path as well as the relative path, but r.js was still unable to locate the file.

This question is pretty old but I see it has a bunch of views, so I figured I'd put this on here as it might help someone out there.

"./js/lib"

javascript - RequireJs: module path does not exist error in build with...

javascript optimization requirejs
Rectangle 27 3

var pool = require('../db');

module.exports.get_plants = function(req, res) {
    // to run a query we can acquire a client from the pool,
    // run a query on the client, and then return the client to the pool
    pool.connect(function(err, client, done) {
        if (err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('SELECT * FROM plants', function(err, result) {
            //call `done()` to release the client back to the pool
            done();
            if (err) {
                return console.error('error running query', err);
            }
            console.log('A call to route: %s', req.route.path + '\nRequest type: ' + req.method.toLowerCase());
            res.json(result);
        });
    });
};

after executing I see the following in the console and I get perfect result in my browser.

Express server listening on port 3000 in development mode
A call to route: /plants
Request type: get

javascript - how to get request path with express req object - Stack O...

javascript node.js express
Rectangle 27 3

I do not know whether you guys found the solution to your problem or not. I was facing the same problem and going nuts to figure out why do I get "jQuery is undefined" error on the plugins i use. I tried all the solutions i get from the internet but no luck at all.

But, suddenly something splash on my mind that may be the script files should be in order. So, I moved the jquery referece to first position and everything start working like charm.

Remember guys, if you're using any plugins with jquery, make sure you use the folloing order of setting reference to those fiels.

Always make sure you must put the jquery reference to first and then the subsequent libraries.

Hope, this solves your problem especially when you use with MasterPages. Its very strange that it works no matter what order you use when you don't use MasterPages but when you do, then it somehow requres the proper order.

Good luck and happy coding,

javascript - ASP.Net Master Page and File path issues - Stack Overflow

asp.net javascript jquery runatserver
Rectangle 27 3

I do not know whether you guys found the solution to your problem or not. I was facing the same problem and going nuts to figure out why do I get "jQuery is undefined" error on the plugins i use. I tried all the solutions i get from the internet but no luck at all.

But, suddenly something splash on my mind that may be the script files should be in order. So, I moved the jquery referece to first position and everything start working like charm.

Remember guys, if you're using any plugins with jquery, make sure you use the folloing order of setting reference to those fiels.

Always make sure you must put the jquery reference to first and then the subsequent libraries.

Hope, this solves your problem especially when you use with MasterPages. Its very strange that it works no matter what order you use when you don't use MasterPages but when you do, then it somehow requres the proper order.

Good luck and happy coding,

javascript - ASP.Net Master Page and File path issues - Stack Overflow

asp.net javascript jquery runatserver
Rectangle 27 3

I do not know whether you guys found the solution to your problem or not. I was facing the same problem and going nuts to figure out why do I get "jQuery is undefined" error on the plugins i use. I tried all the solutions i get from the internet but no luck at all.

But, suddenly something splash on my mind that may be the script files should be in order. So, I moved the jquery referece to first position and everything start working like charm.

Remember guys, if you're using any plugins with jquery, make sure you use the folloing order of setting reference to those fiels.

Always make sure you must put the jquery reference to first and then the subsequent libraries.

Hope, this solves your problem especially when you use with MasterPages. Its very strange that it works no matter what order you use when you don't use MasterPages but when you do, then it somehow requres the proper order.

Good luck and happy coding,

javascript - ASP.Net Master Page and File path issues - Stack Overflow

asp.net javascript jquery runatserver
Rectangle 27 3

/**
 * Two variables should already be set.
 * dropboxToken = OAuth token received then signing in with OAuth.
 * file = file object selected in the file widget.
 */

var xhr = new XMLHttpRequest();

xhr.upload.onprogress = function(evt) {
    var percentComplete = parseInt(100.0 * evt.loaded / evt.total);
    // Upload in progress. Do something here with the percent complete.
};

xhr.onload = function() {
    if (xhr.status === 200) {
        var fileInfo = JSON.parse(xhr.response);
        // Upload succeeded. Do something here with the file info.
    }
    else {
        var errorMessage = xhr.response || 'Unable to upload file';
        // Upload failed. Do something here with the error.
    }
};

xhr.open('POST', 'https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'Bearer ' + dropboxToken);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify({
    path: '/' +  file.name,
    mode: 'add',
    autorename: true,
    mute: false
}));

xhr.send(file);
var downloadFile = function(evt, file) {
  evt.preventDefault();
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'arraybuffer';

  xhr.onload = function() {
    if (xhr.status === 200) {
      var blob = new Blob([xhr.response], {type: application/octet-stream});
      FileSaver.saveAs(blob, file.name, true);
    }
    else {
      var errorMessage = xhr.response || 'Unable to download file';
      // Upload failed. Do something here with the error.
    }
  };

  xhr.open('POST', 'https://content.dropboxapi.com/2/files/download');
  xhr.setRequestHeader('Authorization', 'Bearer ' + dropboxToken);
  xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify({
    path: file.path_lower
  }));
  xhr.send();
}

FileSaver and Blob will not work on older browsers so you could add a workaround to them.

As other answers have noted, each session uploading or downloading the file will need to have access to a dropbox token. Sending someone else's token to a user is a security issue since having the token will give them complete control over the dropbox account. The only way to make this work is to have each person authenticate with Dropbox and get their own token.

At Form.io we've implemented both the authentication and the upload/download into our platform. This makes it really easy to build web apps with dropbox as a backend for files.

javascript - Dropbox direct upload files from browser - Stack Overflow

javascript jquery dropbox dropbox-api dropbox-js
Rectangle 27 2

$("img.phone").attr("src", "../img/template/iphone4.png");

Note that this will replace the source of all images with class phone!

If that is an issue, you should consider to give your image a unique id and change the jquery selector accordingly.

javascript - how can I change path to img src from java script? - Stac...

javascript jquery
Rectangle 27 2

$("img.phone").attr("src", "../img/template/iphone4.png");

Note that this will replace the source of all images with class phone!

If that is an issue, you should consider to give your image a unique id and change the jquery selector accordingly.

javascript - how can I change path to img src from java script? - Stac...

javascript jquery
Rectangle 27 4

let destLatitude="26.9124"
        let destLongitude="75.7873"
        mapView.isMyLocationEnabled = true
        var urlString = "\("https://maps.googleapis.com/maps/api/directions/json")?origin=\("28.7041"),\("77.1025")&destination=\(destLatitude),\(destLongitude)&sensor=true&key=\("Your-Api-key")"

        urlString = urlString.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)!

        let manager=AFHTTPRequestOperationManager()

        manager.responseSerializer = AFJSONResponseSerializer(readingOptions: JSONSerialization.ReadingOptions.allowFragments) as AFJSONResponseSerializer

        manager.requestSerializer = AFJSONRequestSerializer() as AFJSONRequestSerializer

        manager.responseSerializer.acceptableContentTypes = NSSet(objects:"application/json", "text/html", "text/plain", "text/json", "text/javascript", "audio/wav") as Set<NSObject>


        manager.post(urlString, parameters: nil, constructingBodyWith: { (formdata:AFMultipartFormData!) -> Void in

            }, success: {  operation, response -> Void in
                //{"responseString" : "Success","result" : {"userId" : "4"},"errorCode" : 1}
                //if(response != nil){
                let parsedData = JSON(response)
                print_debug("parsedData : \(parsedData)")
               var path = GMSPath.init(fromEncodedPath: parsedData["routes"][0]["overview_polyline"]["points"].string!)
                 //GMSPath.fromEncodedPath(parsedData["routes"][0]["overview_polyline"]["points"].string!)
                var singleLine = GMSPolyline.init(path: path)
                singleLine.strokeWidth = 7
                singleLine.strokeColor = UIColor.green
                singleLine.map = self.mapView
                //let loginResponeObj=LoginRespone.init(fromJson: parsedData)


                //  }
            }, failure: {  operation, error -> Void in

                print_debug(error)
                let errorDict = NSMutableDictionary()
                errorDict.setObject(ErrorCodes.errorCodeFailed.rawValue, forKey: ServiceKeys.keyErrorCode.rawValue as NSCopying)
                errorDict.setObject(ErrorMessages.errorTryAgain.rawValue, forKey: ServiceKeys.keyErrorMessage.rawValue as NSCopying)

        })

not all heroes wear capes!

Google Maps iOS SDK, Getting Directions between 2 locations - Stack Ov...

ios google-maps google-maps-sdk-ios
Rectangle 27 2

/**
 * Two variables should already be set.
 * dropboxToken = OAuth token received then signing in with OAuth.
 * file = file object selected in the file widget.
 */

var xhr = new XMLHttpRequest();

xhr.upload.onprogress = function(evt) {
    var percentComplete = parseInt(100.0 * evt.loaded / evt.total);
    // Upload in progress. Do something here with the percent complete.
};

xhr.onload = function() {
    if (xhr.status === 200) {
        var fileInfo = JSON.parse(xhr.response);
        // Upload succeeded. Do something here with the file info.
    }
    else {
        var errorMessage = xhr.response || 'Unable to upload file';
        // Upload failed. Do something here with the error.
    }
};

xhr.open('POST', 'https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'Bearer ' + dropboxToken);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify({
    path: '/' +  file.name,
    mode: 'add',
    autorename: true,
    mute: false
}));

xhr.send(file);
var downloadFile = function(evt, file) {
  evt.preventDefault();
  var xhr = new XMLHttpRequest();
  xhr.responseType = 'arraybuffer';

  xhr.onload = function() {
    if (xhr.status === 200) {
      var blob = new Blob([xhr.response], {type: application/octet-stream});
      FileSaver.saveAs(blob, file.name, true);
    }
    else {
      var errorMessage = xhr.response || 'Unable to download file';
      // Upload failed. Do something here with the error.
    }
  };

  xhr.open('POST', 'https://content.dropboxapi.com/2/files/download');
  xhr.setRequestHeader('Authorization', 'Bearer ' + dropboxToken);
  xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify({
    path: file.path_lower
  }));
  xhr.send();
}

FileSaver and Blob will not work on older browsers so you could add a workaround to them.

As other answers have noted, each session uploading or downloading the file will need to have access to a dropbox token. Sending someone else's token to a user is a security issue since having the token will give them complete control over the dropbox account. The only way to make this work is to have each person authenticate with Dropbox and get their own token.

At Form.io we've implemented both the authentication and the upload/download into our platform. This makes it really easy to build web apps with dropbox as a backend for files.

javascript - Dropbox direct upload files from browser - Stack Overflow

javascript jquery dropbox dropbox-api dropbox-js
Rectangle 27 31

1) Using <c:url> tag from JSTL

The reason that you get the 404 File Not Found error, is that your path to CSS given as a value to the href attribute is missing context path.

An HTTP request URL contains the following parts:

http://[host]:[port][request-path]?[query-string]

The request path is further composed of the following elements:

There are several solutions to your problem, here are some of them:

In my Java web applications I usually used <c:url> tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).

If you say, that your CSS is located inside WebContent folder, then this should work:

The reason why it works is explained in the "JavaServer Pages Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):

7.5 <c:url> Builds a URL with the proper rewriting rules applied. ... The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.

NOTE Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.

Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.

DISCLAIMER The idea of this solution was taken from here.

To make accessing the context path more compact than in the solution 2, you can first use the JSTL <c:set> tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.

<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />

IMPORTANT NOTE By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.

The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution 3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.

We need a class that implements ServletContextListener interface. Here is an example of such class:

package com.example.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext sc = event.getServletContext();
        sc.setAttribute("ctx", sc.getContextPath());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {}

}

Now in a JSP we can access this global variable using EL:

<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />

NOTE@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    ...  
    <listener>
        <listener-class>com.example.listener.AppContextListener</listener-class>
    </listener>
    ...
</webapp>

As suggested by user @gavenkoa you can also use scriptlets like this:

<%= request.getContextPath() %>

I personally prefer ether the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.

@VishalAnand You are welcome!

You forget about scriplets solution: <%=request.getContextPath()%> )) stackoverflow.com/a/33356037/173149 Alternatively it is possible to write custom JSTL lib with own DSL/sugar.

Well yes, you can use scriptlets in this case although generally using scriptlets in JSP is discouraged. I just offered some of the most common available approaches, I'll mention your suggestion too, thanks.

java - Adding external resources (CSS/JavaScript/images etc) in JSP - ...

java css jsp jstl el
Rectangle 27 31

1) Using <c:url> tag from JSTL

The reason that you get the 404 File Not Found error, is that your path to CSS given as a value to the href attribute is missing context path.

An HTTP request URL contains the following parts:

http://[host]:[port][request-path]?[query-string]

The request path is further composed of the following elements:

There are several solutions to your problem, here are some of them:

In my Java web applications I usually used <c:url> tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).

If you say, that your CSS is located inside WebContent folder, then this should work:

The reason why it works is explained in the "JavaServer Pages Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):

7.5 <c:url> Builds a URL with the proper rewriting rules applied. ... The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.

NOTE Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.

Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.

DISCLAIMER The idea of this solution was taken from here.

To make accessing the context path more compact than in the solution 2, you can first use the JSTL <c:set> tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.

<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />

IMPORTANT NOTE By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.

The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution 3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.

We need a class that implements ServletContextListener interface. Here is an example of such class:

package com.example.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext sc = event.getServletContext();
        sc.setAttribute("ctx", sc.getContextPath());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {}

}

Now in a JSP we can access this global variable using EL:

<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />

NOTE@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    ...  
    <listener>
        <listener-class>com.example.listener.AppContextListener</listener-class>
    </listener>
    ...
</webapp>

As suggested by user @gavenkoa you can also use scriptlets like this:

<%= request.getContextPath() %>

I personally prefer ether the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.

@VishalAnand You are welcome!

You forget about scriplets solution: <%=request.getContextPath()%> )) stackoverflow.com/a/33356037/173149 Alternatively it is possible to write custom JSTL lib with own DSL/sugar.

Well yes, you can use scriptlets in this case although generally using scriptlets in JSP is discouraged. I just offered some of the most common available approaches, I'll mention your suggestion too, thanks.

java - Adding external resources (CSS/JavaScript/images etc) in JSP - ...

java css jsp jstl el