I have a folder named "images" in the same directory as my .js file. I want to load all the images from "images" folder into my html page using Jquery/Javascript.
Since, names of images are not some successive integers, how am I supposed to load these images?
Works both localhost and on live server without issues, and allows you to extend the delimited list of allowed file-extensions:
var folder = "images/";
$.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 +"'>" );
}
});
}
});
NOTICE
Apache server has Option Indexes turned on by default - if you use another server like i.e. Express for Node you could use this NPM package for the above to work: https://github.com/expressjs/serve-index
If the files you want to get listed are in /images than inside your server.js you could add something like:
const express = require('express');
const app = express();
const path = require('path');
// Allow assets directory listings
const serveIndex = require('serve-index');
app.use('/images', serveIndex(path.join(__dirname, '/images')));
Use :
var dir = "Src/themes/base/images/";
var fileextension = ".png";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function (data) {
//List all .png file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http://", "");
$("body").append("<img src='" + dir + filename + "'>");
});
}
});
If you have other extensions, you can make it an array and then go through that one by one using in_array().
P.s : The above source code is not tested.
This is the way to add more file extentions, in the example given by Roy M J in the top of this page.
var fileextension = [".png", ".jpg"];
$(data).find("a:contains(" + (fileextension[0]) + "), a:contains(" + (fileextension[1]) + ")").each(function () { // here comes the rest of the function made by Roy M J
In this example I have added more contains.
If interested in doing this without jQuery - here's a pure JS variant (from here) of the answer currently most upvoted:
var xhr = new XMLHttpRequest();
xhr.open("GET", "/img", true);
xhr.responseType = 'document';
xhr.onload = () => {
if (xhr.status === 200) {
var elements = xhr.response.getElementsByTagName("a");
for (x of elements) {
if ( x.href.match(/\.(jpe?g|png|gif)$/) ) {
let img = document.createElement("img");
img.src = x.href;
document.body.appendChild(img);
}
};
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
}
xhr.send()
Here is one way to do it. Involves doing a little PHP as well.
The PHP part:
$filenameArray = [];
$handle = opendir(dirname(realpath(__FILE__)).'/images/');
while($file = readdir($handle)){
if($file !== '.' && $file !== '..'){
array_push($filenameArray, "images/$file");
}
}
echo json_encode($filenameArray);
The jQuery part:
$.ajax({
url: "getImages.php",
dataType: "json",
success: function (data) {
$.each(data, function(i,filename) {
$('#imageDiv').prepend('<img src="'+ filename +'"><br>');
});
}
});
So basically you do a PHP file to return you the list of image filenames as JSON, grab that JSON using an ajax call, and prepend/append them to the html. You would probably want to filter the files u grab from the folder.
Had some help on the php part from 1
$(document).ready(function(){
var dir = "test/"; // folder location
var fileextension = ".jpg"; // image format
var i = "1";
$(function imageloop(){
$("<img />").attr('src', dir + i + fileextension ).appendTo(".testing");
if (i==13){
alert('loaded');
}
else{
i++;
imageloop();
};
});
});
For this script, I have named my image files in a folder as 1.jpg, 2.jpg, 3.jpg, ... to 13.jpg.
You can change directory and file names as you wish.
Based on the answer of Roko C. Buljan, I have created this method which gets images from a folder and its subfolders . This might need some error handling but works fine for a simple folder structure.
var findImages = function(){
var parentDir = "./Resource/materials/";
var fileCrowler = function(data){
var titlestr = $(data).filter('title').text();
// "Directory listing for /Resource/materials/xxx"
var thisDirectory = titlestr.slice(titlestr.indexOf('/'), titlestr.length)
//List all image file names in the page
$(data).find("a").attr("href", function (i, filename) {
if( filename.match(/\.(jpe?g|png|gif)$/) ) {
var fileNameWOExtension = filename.slice(0, filename.lastIndexOf('.'))
var img_html = "<img src='{0}' id='{1}' alt='{2}' width='75' height='75' hspace='2' vspace='2' onclick='onImageSelection(this);'>".format(thisDirectory + filename, fileNameWOExtension, fileNameWOExtension);
$("#image_pane").append(img_html);
}
else{
$.ajax({
url: thisDirectory + filename,
success: fileCrowler
});
}
});}
$.ajax({
url: parentDir,
success: fileCrowler
});
}
This is the code that works for me, what I want is to list the images directly on my page so that you just have to put the directory where you can find the images for example -> dir = "images /"
I do a substring var pathName = filename.substring (filename.lastIndexOf ('/') + 1);
with which I make sure to just bring the name of the files listed and at the end I link my URL to publish it in the body
$ ("body"). append ($ ("<img src =" + dir + pathName + "> </ img>"));
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src="jquery-1.6.3.min.js"></script>
<script>
var dir = "imagenes/";
var fileextension = ".jpg";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: dir,
success: function (data) {
//Lsit all png file names in the page
$(data).find("a:contains(" + fileextension + ")").each(function () {
var filename = this.href.replace(window.location.pathname, "").replace("http://", "");
var pathName = filename.substring(filename.lastIndexOf('/') + 1);
$("body").append($("<img src=" + dir + pathName + "></img>"));
console.log(dir+pathName);
});
}
});
</script>
</head>
<body>
<img src="1_1.jpg">
</body>
</html>
If, as in my case, you would like to load the images from a local folder on your own machine, then there is a simple way to do it with a very short Windows batch file. This uses the ability to send the output of any command to a file using > (to overwrite a file) and >> (to append to a file).
Potentially, you could output a list of filenames to a plain text file like this:
dir /B > filenames.txt
However, reading in a text file requires more faffing around, so I output a javascript file instead, which can then be loaded in your to create a global variable with all the filenames in it.
echo var g_FOLDER_CONTENTS = mlString(function() { /*! > folder_contents.js
dir /B images >> folder_contents.js
echo */}); >> folder_contents.js
The reason for the weird function with comment inside notation is to get around the limitation on multi-line strings in Javascript. The output of the dir command cannot be formatted to write a correct string, so I found a workaround here.
function mlString(f) {
return f.toString().
replace(/^[^\/]+\/\*!?/, '').
replace(/\*\/[^\/]+$/, '');
}
Add this in your main code before the generated javascript file is run, and then you will have a global variable called g_FOLDER_CONTENTS, which is a string containing the output from the dir command. This can then be tokenized and you'll have a list of filenames, with which you can do what you like.
var filenames = g_FOLDER_CONTENTS.match(/\S+/g);
Here's an example of it all put together: image_loader.zip
In the example, run.bat generates the Javascript file and opens index.html, so you needn't open index.html yourself.
NOTE: .bat is an executable type in Windows, so open them in a text editor before running if you are downloading from some random internet link like this one.
If you are running Linux or OSX, you can probably do something similar to the batch file and produce a correctly formatted javascript string without any of the mlString faff.
You can't do this automatically. Your JS can't see the files in the same directory as it.
Easiest is probably to give a list of those image names to your JavaScript.
Otherwise, you might be able to fetch a directory listing from the web server using JS and parse it to get the list of images.
In jQuery you can use Ajax to call a server-side script. The server-side script will find all the files in the folder and return them to your html file where you will need to process the returned information.
You can use the fs.readdir or fs.readdirSync methods to get the file names in the directory.
The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.
The second is synchronous, it will returns the file name array, but it will stop any further execution of your code until the read process ends.
After that you simply have to iterate through the names and using append function, add them to their appropriate locations. To check out how it works see HTML DOM and JS reference
Add the following script:
<script type="text/javascript">
function mlString(f) {
return f.toString().
replace(/^[^\/]+\/\*!?/, '');
replace(/\*\/[^\/]+$/, '');
}
function run_onload() {
console.log("Sample text for console");
var filenames = g_FOLDER_CONTENTS.match(/\S+/g);
var fragment = document.createDocumentFragment();
for (var i = 0; i < filenames.length; ++i) {
var extension = filenames[i].substring(filenames[i].length-3);
if (extension == "png" || extension == "jpg") {
var iDiv = document.createElement('div');
iDiv.id = 'images';
iDiv.className = 'item';
document.getElementById("image_div").appendChild(iDiv);
iDiv.appendChild(fragment);
var image = document.createElement("img");
image.className = "fancybox";
image.src = "images/" + filenames[i];
fragment.appendChild(image);
}
}
document.getElementById("images").appendChild(fragment);
}
</script>
then create a js file with the following:
var g_FOLDER_CONTENTS = mlString(function() { /*!
1.png
2.png
3.png
*/});
Using Chrome, searching for the images files in links (as proposed previously) didn't work as it is generating something like:
(...) i18nTemplate.process(document, loadTimeData);
</script>
<script>start("current directory...")</script>
<script>addRow("..","..",1,"170 B","10/2/15, 8:32:45 PM");</script>
<script>addRow("fotos-interessantes-11.jpg","fotos-interessantes-> 11.jpg",false,"","");</script>
Maybe the most reliable way is to do something like this:
var folder = "img/";
$.ajax({
url : folder,
success: function (data) {
var patt1 = /"([^"]*\.(jpe?g|png|gif))"/gi; // extract "*.jpeg" or "*.jpg" or "*.png" or "*.gif"
var result = data.match(patt1);
result = result.map(function(el) { return el.replace(/"/g, ""); }); // remove double quotes (") surrounding filename+extension // TODO: do this at regex!
var uniqueNames = []; // this array will help to remove duplicate images
$.each(result, function(i, el){
var el_url_encoded = encodeURIComponent(el); // avoid images with same name but converted to URL encoded
console.log("under analysis: " + el);
if($.inArray(el, uniqueNames) === -1 && $.inArray(el_url_encoded, uniqueNames) === -1){
console.log("adding " + el_url_encoded);
uniqueNames.push(el_url_encoded);
$("#slider").append( "<img src='" + el_url_encoded +"' alt=''>" ); // finaly add to HTML
} else{ console.log(el_url_encoded + " already in!"); }
});
},
error: function(xhr, textStatus, err) {
alert('Error: here we go...');
alert(textStatus);
alert(err);
alert("readyState: "+xhr.readyState+"\n xhrStatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I everyone, I want to know how to upload a File in HTML5, without Input file, or at least without clicking on it. If there is a way to put it in without clicks and searching fo it, I would like to hear about it.
The thing is, in HTML5 I have a table, when is clicked it opens a modal with info, that info is sent by AJAX to a .jsp file, where I create a PDF using the info, in a certain path. I want to use the same file to upload it with a WCF service, but all what I could do was to create it, and then to look for it with an input file, but I want to use it with out the input file.
Here is some of my code...
The JSP File where I create the PDF file:
<%
String idP = request.getParameter("idP");
String nombreP = request.getParameter("NombreP");
String nombreC = request.getParameter("NombreC");
String presupuesto = request.getParameter("Presupuesto");
String avance = request.getParameter("Avacne");
String empleado = request.getParameter("Empleado");
String constructora = request.getParameter("Constructora");
String idC = request.getParameter("idC");
String idE = request.getParameter("idE");
String idT = request.getParameter("idT");
Font GreenFont = FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new CMYKColor(0, 0, 255, 0));
Font yellowFont = FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new CMYKColor(255, 0, 255, 0));
String path = "E:" + File.separator + "Reportes" + File.separator + "Reporte " + nombreP + ".pdf";
Document document = new Document();
File file = new File(path);
try {
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file.getPath()));
document.open();
Paragraph chapterTitle = new Paragraph(nombreP, yellowFont);
Chapter chapter1 = new Chapter(chapterTitle, 1);
chapter1.setNumberDepth(0);
document.add(chapter1);
document.add(new Paragraph("Nombre cliente:" + nombreC));
document.add(new Paragraph("Presupuesto: $" + presupuesto));
document.add(new Paragraph("Avance del proyecto: %" + avance));
document.add(new Paragraph("Nombre del empleado: " + empleado));
document.add(new Paragraph("Constructora: " + constructora));
document.add(new Paragraph("Id_Proyecto: " + idP));
document.add(new Paragraph("Id_Constructora: " + idC));
document.add(new Paragraph("Id_Empleado: " + idE));
document.add(new Paragraph("Id_Tipo: " + idT));
document.addAuthor("Erick Adahir");
document.addCreationDate();
document.addCreator("LorCyC");
document.addTitle("AVAVAGO");
document.addSubject("Un simple ejemplo");
document.close();
writer.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
%>
The function that calls the JSP:
function agregarEventoDoubleClickEnTablaProyecto()
{
$('#tablaProyecto td').dblclick(function ()
{
var $this = $(this);
var row = $this.closest("tr"); //Hacemos referencia al registro padre de la celda
//alert(row.find('td:eq(0)').text());
//row.find('td:firs').text();
alert("PDF");
$.ajax({
url: "Proyecto/creaPDF.jsp",
data: {
idP: id,
NombreP: row.find('td:eq(1)').text(),
NombreC: row.find('td:eq(2)').text(),
Presupuesto: row.find('td:eq(3)').text(),
Avance: row.find('td:eq(4)').text(),
Tipo: row.find('td:eq(5)').text(),
Empleado: row.find('td:eq(6)').text(),
Constructora: row.find('td:eq(7)').text(),
idC: row.find('td:eq(8)').text(),
idE: row.find('td:eq(9)').text(),
idT: row.find('td:eq(10)').text()
}
}).done(function (data) {
alert("nice...");
});
$('#areaDatosProyecto').modal({
show: 'true'
});
});
}
And finally, the function that uploads the File using Input File:
function subir() {
var archivo = document.getElementById("btnFile").files[0];
alert(archivo);
var fr = new FileReader();
fr.onload = function () {
var bString = this.result;
var objUp = {
elemento: {
NombreOriginal: "nombre",
Documento: bString.split("base64,")[1]
}
};
$.ajax({
url: "http://localhost:84/Uploader/ServicioUploader.svc/ArchivarDocumento",
data: JSON.stringify(objUp),
dataType: "json",
type: "POST",
contentType: "application/json; charset=UTF-8",
success: function (data) {
var id = data.d;
alert(id);
},
error: function (xnr, status, error) {
alert("XNR: " + xnr + ", STATUS: " + status + ", ERROR: " + error);
}
});
};
fr.readAsDataURL(archivo);
}
Hope someone can lend me a hand! Thanks!
You are creating the file inside a JSP.
Which means that it should be created on the path (E:/Reportes/Reporte/[your filename].pdf) where your server is hosted.
You can write the code for upload right there in your JSP itself (where the file object is being created).
I dont see a point of two AJAX calls.
I am not 100% sure I understand what you're trying to do, but If I am understanding your issue correctly, it sounds like you are creating this PDF "server side" on your own system, and saving it to disk, and then on the same system loading up a "client side" web app where you have an upload control (i.e. file selector) where the user selects the PDF that is then uploaded to another server, but you are trying to avoid needing the user to manually select the file to upload in the final step.
If this is your case, unfortunately you cannot do that because it is a security risk, any modern browser will not allow you to programmatically upload a file from a user's hard drive without their manual selection of the file.
SO, not to try and be negative, but it sounds like you may be going about this the wrong way. Why don't you create AND upload the PDF from your server-side (JSP) code? It seems like adding in the client-side web app here is unnecessary. Since you already know WHERE to send the PDF (your URL looks hard-coded there) and you apparently control the server side code, it seems the simplest solution would be to just open an HTTPUrlConnection (or use whatever library you may like) to send the raw bytes of the PDF to it's final destination.
2nd question I've posted. still very new to web programming so excuse my ignorance.
I have a web based javascript which accesses a users Gmail account and downloads attachments to the local downloads folder as assigned in Chrome.
These files are then manually transferred to another directory and an Excel VBA script processes the files.
I'd like to be able to skip the manual transfer step and save the files directly to to the folder that Excel is looking at. I can get the Excel script to move the files but it only works if the user has not changed the Chrome default downloads folder location so it's not foolproof.
I believe this is impossible with javascript but is it possible with other languages or do I need a completely different approach? if it is possible with other languages which one and which methods do I need to be looking at?
This is the download section of the code as it stands at the minute at the request of a user OmegaStripes below:
<html>
<head>Google Drive File Download Process:
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<script type="text/javascript">
var CLIENT_ID = 'XXXXXXXXXXX';//removed for privacy
var SCOPES = 'https://www.googleapis.com/auth/drive';
/**
* Called when the client library is loaded to start the auth flow.
*/
function handleClientLoad() {
window.setTimeout(checkAuth, 1);
}
/**
* Check if the current user has authorized the application.
*/
function checkAuth() {
gapi.auth.authorize({
'client_id': CLIENT_ID,
'scope': SCOPES,
'immediate': true
},
handleAuthResult);
}
/**
* Called when authorization server replies.
*
*/
function handleAuthResult(authResult) {
var authButton = document.getElementById('authorizeButton');
var filePicker = document.getElementById('filePicker');
authButton.style.display = 'none';
filePicker.style.display = 'none';
if (authResult && !authResult.error) {
// Access token has been successfully retrieved, requests can be sent to the API.
filePicker.style.display = 'block';
filePicker.onclick = downloadFile; // to allow for manual start of downloads
window.setTimeout(downloadFile(), 5000);
} else {
// No access token could be retrieved, show the button to start the authorization flow.
authButton.style.display = 'block';
authButton.onclick = function() {
gapi.auth.authorize({
'client_id': CLIENT_ID,
'scope': SCOPES,
'immediate': false
},
handleAuthResult);
};
}
}
/**
* Start the file download.
*
*
*/
function downloadFile() {
console.log("call drive api");
gapi.client.load('drive', 'v2', makeRequest);
}
function makeRequest() {
console.log("make request");
var request = gapi.client.drive.files.list();
request.execute(function(resp) {
var x = []; //array for revised list of files to only include those not in the trash and those which have a suffix #FHM#
for (i = 0; i < resp.items.length; i++) {
if (resp.items[i].labels.trashed != true && resp.items[i].title.substring(0, 5) == "#FHM#") {
x.push([resp.items[i].title, resp.items[i].webContentLink, resp.items[i].id]);
}
}
if (x.length == 0) {
document.getElementById("filePicker").value = "There are no files to download";
}
for (i = 0; i < x.length; i++) {
console.log(x.length);
var dlUrl = x[i][1];
fileIdentity = x[i][2];
downloadUrl(dlUrl);
trashFile(fileIdentity);
filePicker.style.display = 'none';
document.getElementById("bodyText").innerHTML = "<br>Download " + (i + 1) + " of " + x.length + " completed.";
}
});
//window.setTimeout(function() {
// self.close;
//}, 5000);
}
function downloadUrl(url) {
var iframe = document.createElement("iframe");
iframe.src = url;
iframe.style.display = "none";
document.body.appendChild(iframe);
}
function trashFile(id) {
var requestTrash = gapi.client.drive.files.trash({
'fileId': id
});
requestTrash.execute(function(resp) {});
}
</script>
<script type="text/javascript" src="https://apis.google.com/js/client.js?onload=handleClientLoad"></script>
</head>
<body>
<!--Add buttons for the user to start the process -->
<input type="button" id="filePicker" style="display: none" value="If download does not start after 5 seconds, click here" />
<input type="button" id="authorizeButton" style="display: none" value="Authorize" />
<b id="bodyText"></b>
</body>
thanks
Your code could try to copy the files and if unsuccessful, ask the user to provide the correct path to the extracted file(s). You are right it cannot be done by Javascript. If you want to avoid having to ask the user for the path, you can implement a module to search for the file.
Is there a way you could know whether a file was extracted? If so, you can use this knowledge to know whether the lack of successful copying should trigger a file search or file path requesting.
I tried to read an RSS feed from an external website with the following code:
$.get('http://myrssurl.com',function (XMLmediaArray) {
$(XMLmediaArray).find('item').each(function() {
var item = $(this);
var title = item.find('title').text();
var description = item.find('description').text();
var link = item.find('link').text();
var image = item.find('enclosure[type="image/jpeg"]').attr('url');
});
});
I got an error message which says:
XMLHttpRequest cannot load http://myrssurl.com. No '*Access-Control-Allow-Origin*' header is present on the requested resource. Origin 'localhost is therefore not allowed access.
Do you know how to solve this?
Thanks for your help! in the meanwhile I tried to use the GOOGLE RSS FEED service but I also have to deal with a problem by using this:
in the html file I'm using this:
<script type="text/javascript">
new rssdisplayer("msndiv","http://www.myrssfeedurl",6,"date, description");
</script>
and in the Javascript file the follow:
google.load("feeds", "1"); //Load Google Ajax Feed API (version 1)
function rssdisplayer(divid, url, feedlimit, showoptions){
this.showoptions=showoptions || "" //get string of options to show ("date" and/or "description"wink
var feedpointer=new google.feeds.Feed(url) //create new instance of Google Ajax Feed API
feedpointer.setNumEntries(feedlimit) //set number of items to display
document.write('<div id="'+divid+'">Loading feed, </div>')
this.feedcontainer=document.getElementById(divid)
var displayer=this
feedpointer.load(function(r){displayer.formatoutput(r)}) //call Feed.load() to retrieve and output RSS feed
}
rssdisplayer.prototype.formatdate=function(datestr){
var itemdate=new Date(datestr)
return "<span style='color:gray; font-size: 90%'>"+itemdate.toLocaleString()+"</span>"
}
rssdisplayer.prototype.formatoutput=function(result){
if (!result.error){ //if RSS feed successfully fetched
var thefeeds=result.feed.entries //get all feed entries as a JSON array
var rssoutput="<ul>"
for (var i=0; i<thefeeds.length; i++){ //loop through entries
var itemtitle="" + thefeeds[i].title + ""
var itemdate=/date/i.test(this.showoptions)? this.formatdate(thefeeds[i].publishedDate) : ""
var itemdescription=/description/i.test(this.showoptions)? "<br />"+thefeeds[i].content : ""
rssoutput+="<li>" + itemtitle + " " + itemdate + itemdescription + "</li>"
}
rssoutput+="</ul>"
this.feedcontainer.innerHTML=rssoutput
}
else //else, output error
alert("Error fetching feeds: "+result.error.message)
}
but when I execute it in the Browser I get this error message:
Uncaught ReferenceError: rssdisplayer is not defined (index):127 (anonymous function)
Do you guys know what the issue is?
This is an AJAX security: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
You are not allowed to query on other websites.
I would recommend to parse the RSS feed on your server and re-format it in JSON for convenience.
I solved it with the Google API RSS Feed Service. The error came because the rssdisplayer.js file was included too late in the html file. Include it directly after the jquery mobile javascript
I'm working with Skydrive APIs, and I would like my user tobe able to open a view about a file where you can edit it (the same view as we can have about a file when you're on the skydrive web page).
There may be a WL function for it but I can't find it. An other solution would be for me to get the URL of the view page and open it in a new window with javascript.
I have implemented this solution using SkyDrive and its API. You can try this script out within Microsoft's Interactive Live SDK online tool as well. The key is to obtain SkyDrive's redirect link for the file you are looking to open. This redirect link is returned for each file in the Get api's json result.
Processing Steps:
Initializes Windows Live jscript api client
Authenticate with Windows Live (skydrive) OAuth
GetFiles: Get a list of all files within your SkyDrive account. This could be adjusted for your needs and focused to just get a list for a specific folder with your SkyDrive account
onFilesComplete: iterate through json response looking for an item with a type='file' and file name you are looking to open. In this, case a file name 'robots.txt'
display details about the found file
using the found file's "link" attribute, open url in a new window browser window. This will open the file using SkyDrive default action. For known file types such as code files, this will open them in SkyDrive's online file editor. Otherwise, the default action will be to download the found file
Example Code:
WL.init({ client_id: clientId, redirect_uri: redirectUri });
WL.login({ "scope": "wl.skydrive" }).then(
function(response) {
getFiles();
},
function(response) {
log("Could not connect, status = " + response.status);
}
);
function getFiles() {
var files_path = "/me/skydrive/files";
WL.api({ path: files_path, method: "GET" }).then(
onGetFilesComplete,
function(response) {
log("Cannot get files and folders: " +
JSON.stringify(response.error).replace(/,/g, ",\n"));
}
);
}
function onGetFilesComplete(response) {
var items = response.data;
var foundFolder = 0;
for (var i = 0; i < items.length; i++) {
if (items[i].type === "file" &&
items[i].name === "robots.txt") {
log("Found a file with the following information: " +
JSON.stringify(items[i]).replace(/,/g, ",\n"));
foundFolder = 1;
//open file in a new browser window
window.open(items[i].link);
break;
}
}
if (foundFolder == 0) {
log("Unable to find any file(s)");
}
}
function log(message) {
var child = document.createTextNode(message);
var parent = document.getElementById('JsOutputDiv') || document.body;
parent.appendChild(child);
parent.appendChild(document.createElement("br"));
}