Read a local xml file to a string in Javascript - javascript

I'm surprised to see that this is hard to do, but i haven't found a single way to do that.
Basically i have a directory that contains:
--index.html
--script.js
--file.xml
And i want to read the content of the file.xml to a JS string for parsing.
The only method i found of doing so was by using a synchronous xmlhttp object which is disabled by default in my browser.
Is there another (preferably easy) way of reading a file to a string in js?

So, I might be a little late to the party, but this is to help anybody else who's been ripping his/her hair out looking for a solution to this.
First of all, CORS needs to be allowed in the browser if you're not running your HTML file off a server. Second, I found that the code snippets most people refer to in these kind of threads don't work for loading local XML-files. Try this (example taken from the official docs):
var xhr = new XMLHttpRequest();
xhr.open('GET', 'file.xml', true);
xhr.timeout = 2000; // time in milliseconds
xhr.onload = function () {
// Request finished. Do processing here.
var xmlDoc = this.responseXML; // <- Here's your XML file
};
xhr.ontimeout = function (e) {
// XMLHttpRequest timed out. Do something here.
};
xhr.send(null);
The method (1st arg) is ignored in xhr.open if you're referring to a local file, and async (3rd arg) is true by default, so you really just need to point to your file and then parse the result! =)
Good luck!

Related

How do you load data from a text file into a variable in javascript

I'm just trying to do something that simple. All I want to do is load the contents of a text file into a variable. The text file is only one line and is always a string. I know there are other threads asking the same question, but as of now, the closest answer I have gotten is this:
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
The problem with this is that I am trying to load the information into a variable. Not send it as an alert. I have tried this:
var string;
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
string = client.responseText;
}
client.send();
This does not work either.
This is not a duplicate of this post, as that post is focused on Ajax, and doesn't actually answer how to import the information. I'm not utilizing Ajax. I want the information from the file to be usable elsewhere in the program.
it is evident that you are trying to make an HTTP request to the user's local computer and for obvious reasons - browsers do not allow this! else hackers would be able to read the entire content of a users C drive if they wanted - or worse!
So - you are required to upload the file! i.e. <input type="file" id="uploadFile" /> Check this JSFiddle, you would use the onChange event of the input to read the file
For a similar situation, I used file upload to the server and used PHP/c# (cant remember off the top of my head) which returned the required data - this made things a bit easier actually - the server would receive the file and validate, extract required information and return just the required data - although it seems like more work on the server side - which it is a little bit more you can plan it to make reduce the amount of javascript code you might have to write.

'Access is denied' exception trying to download binary file stream

I am receiving an XmlHttpRequest's response in my code, which is a binary stream of a file. The response has the correct size and mimetype. I would like to download this file to disk, by issuing the typical browser prompt for saving files. I have the following script in place which works perfectly fine in Chrome. It fails for IE though.
var url = /my_rest_url/;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.onreadystatechange = function (e) {
if (xhr.readyState == xhr.DONE) {
var blob = xhr.response;
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
}
}
xhr.send();
The failure happens on the window.open() call, where IE fails with an exception that says "access is denied". I have researched for hours on end without finding a solution which works for me. I have seen some recommendations to use a 'hidden iframe' to start the download, but it hasn't worked out for me. Has anyone ever made something like this work in IE? Would be glad to get some ideas.
ps/ I know blob and createObjectURL are relatively new. And even though they are supported by IE10 and above, I would really feel better to get rid of these and achieve this an 'old-school' way, if there is any.

Reading a text file line by line in java script, xmlhttprequest not defined?

I am new to javascript and simply trying to read a text file and print out its contents line by line.
function readTextFile(file)
{
var client = new XMLHttpRequest();
client.open('GET', file);
client.send();
client.onreadystatechange = function() {
alert(client.responseText);
}
}
readTextFile("file.txt");
I know alert(client.responseText) isn't reading it line by line, but I am taking it step by step. I'm not even sure if XMLHttpRequest is the way to do this but its what I have been seeing when I search around for some help.
The error message I get off the bat is:
ReferenceError: XMLHttpRequest is not defined
I'm not to sure what this means or why it isn't defined. Do I have to import something to use this? How do I even import namespaces or assemblies in javascript at all?
Thanks

Make browser download/save files without user interaction

I need to create a small browser-based application that helps users download/save, and possibly print to the default printer, a large number of files from a webserver we have no control over (but we have all the URIs beforehand).
These files are hidden behind a "single sign-on" (SSO) that can only be performed via a browser and requires a user. Hence, it must be a browser-based solution, where we piggyback on to the session established by the SSO.
The users' platform is Windows 7.
The point is to save the users from going through a lot of clicks per file (download, where to save, etc.) when they need to perform this operation (daily).
At this point all the files are PDF, but that might change in the future.
A browser-agnostic solution is preferred (and I assume more robust when it comes to future browser updates).
But we can base it on a particular browser if needed.
How would you do this from Javascript?
As the comments to my question says, this isn't really allowed by the browsers for security reasons.
My workaround for now (only tested using IE11) is to manually change the security settings of the users browser, and then download the files as a blob into a javascript variable using AJAX, followed by upload of same blob to my own server again using AJAX.
"My own server" is a Django site created for this purpose, that also knows which files to download for the day, and provide the javascript needed. The user goes to this site to initiate the daily download after performing the SSO in a separate browser tab.
On the server I can then perform whatever operations needed for said files.
Many thanks to this post https://stackoverflow.com/a/13887220/833320 for the handling of binary data in AJAX.
1) In IE, add the involved sites to the "Local Intranet Zone", and enable "Access data sources across domains" for this zone to overcome the CORS protection otherwise preventing this.
Of course, consider the security consequences involved in this...
2) In javascript (browser), download the file as a blob and POST the resulting data to my own server:
var x = new XMLHttpRequest();
x.onload = function() {
// Create a form
var fd = new FormData();
fd.append('csrfmiddlewaretoken', '{{ csrf_token }}'); // Needed by Django
fd.append('file', x.response); // x.response is a Blob object
// Upload to your server
var y = new XMLHttpRequest();
y.onload = function() {
alert('File uploaded!');
};
y.open('POST', '/django/upload/');
y.send(fd);
};
x.open('GET', 'https://external.url', true);
x.responseType = 'blob'; // <-- This is necessary!
x.send();
3) Finally (in Django view for '/django/upload/'), receive the uploaded data and save as file - or whatever...
filedata = request.FILES['file'].read()
with open('filename', 'wb') as f:
f.write(filedata)
Thanks all, for your comments.
And yes, the real solution would be to overcome the SSO (that requieres the user), so it all could be done by the server itself.
But at least I learned a little about getting/posting binary data using modern XMLHttpRequests. :)
Actually, I had a problem like it, I wanted to download a binary file(an image) and store it and then use it when I need it, So I decided to download it with Fetch API Get call:
const imageAddress = 'an-address-to-my-image.jpg'; // sample address
fetch(imageAddress)
.then(res => res.blob) // <-- This is necessary!
.then(blobFileToBase64)
.then(base64FinalAnswer => console.log(base64FinalAnswer))
The blobFileToBase64 is a helper function that converts blob binary file to a base64 data string:
const blobToBase64 = blob => {
const reader = new FileReader();
reader.readAsDataURL(blob);
return new Promise(resolve => {
reader.onloadend = () => {
resolve(reader.result);
};
});
};
In the end, I have the base64FinalAnswer and I can do anything with it.

Using Web Audio API decodeAudioData with external binary data

I've searched related questions but wasn't able to find any relevant info.
I'm trying to get the Web Audio API to play an mp3 file which is encoded in another file container, so what I'm doing so far is parsing said container, and feeding the result binary data (arraybuffer) to the audioContext.decodeAudioData method, which supposedly accepts any kind of arraybuffer containing audio data. However, it always throws the error callback.
I only have a faint grasp of what I'm doing so probably the whole approach is wrong. Or maybe it's just not possible.
Has any of you tried something like this before? Any help is appreciated!
Here's some of the code to try to illustrate this better. The following just stores the arraybuffer:
newFile: function(filename){
var that=this;
var oReq = new XMLHttpRequest();
oReq.open("GET", filename, true);
oReq.responseType = "arraybuffer";
oReq.onload = function (oEvent) {
var arrayBuffer = oReq.response; //
if (arrayBuffer) {
that.arrayBuffer=arrayBuffer;
that.parsed=true;
}
};
oReq.send(null);
And this is what I'm doing in the decoding part:
newTrack: function(tracknumber){
var that=this;
var arraybuffer=Parser.arrayBuffer;
that.audioContext.decodeAudioData(arraybuffer,function(buffer){
var track={};
track.trackBuffer=buffer;
track.isLoaded=true;
track.trackSource=null;
track.gainNode=that.audioContext.createGainNode();
that.tracklist.push(track);
},alert('error'));
Where Parser is an object literal that I've used to parse and store the arraybuffer (which has the newFile function)
So, to sum up, I don't know if I'm doing something wrong or it simply cannot be done.
Without the container, I'm not sure how decodeAudioData would know that it's an MP3. Or what the bitrate is. Or how many channels it has. Or a lot of other pretty important information. Basically, you need to tell decodeAudioData how to interpret that ArrayBuffer.
The only thing I could think of on the client side is trying to use a Blob. You'd basically have to write the header yourself, and then readAsArrayBuffer before passing it in to decodeAudioData.
If you're interested in trying that out, here's a spec:
http://www.mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm
And here's RecorderJS, which would show you how to create the Blob (although it writes RIFF/WAV headers instead of MP3):
https://github.com/mattdiamond/Recorderjs/blob/master/recorderWorker.js
You'd want to look at the encodeWAV method.
Anyway, I would strongly recommend getting this sorted out on the server instead, if you can.

Categories