audio file and json file reading methods difference in javascript - javascript

I find difficult to understand one methodological thing about javascript coding.
When in a script I want to read an audio file, I do it like this:
var audio = new Audio('theme.mp3');
audio.play();
It is simple, clear and works dynamically: I have an access to a file system from the site (is it true?).
But if I'd like to read a json file, which is substantially a text file, I have to write an AJAX request:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
//code
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
And also using jQuery we see the same but shorten thing.
Could you explain me, why I can read all the graphics, audio files etc, but to upload JSON file I have to do that request? How does this kind of communication between client and server work? Where is a difference? Why I can't just read the text file, like I did it above with theme.mp3?
Thank you so much.
UPDATE:
The most important thing: when I read the audio file as above, the script is working nicely even if I open the html file from the computer. At the same time the loading of JSON file doesn't work until the page is opened from the localhost. (I'm sorry if I use incorrect terms).
"Help me StackOverflow, you are the my last hope."

Related

How to post blob and string with XMLHttpRequest javascript and PHP [duplicate]

I've seen many partial answers to this here and elsewhere, but I am very much a novice coder and am hoping for a thorough solution. I have been able to set up recording audio from a laptop mic in Chrome Canary (v. 29.x) and can, using recorder.js, relatively easily set up recording a .wav file and saving that locally, a la:
http://webaudiodemos.appspot.com/AudioRecorder/index.html
But I need to be able to save the file onto a Linux server I have running. It's the actual sending of the blob recorded data to the server and saving it out as a .wav file that's catching me up. I don't have the requisite PHP and/or AJAX knowledge about how to save the blob to a URL and to deal, as I have been given to understand, with binaries on Linux that make saving that .wav file challenging indeed. I'd greatly welcome any pointers in the right direction.
Client side JavaScript function to upload the WAV blob:
function upload(blob) {
var xhr=new XMLHttpRequest();
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("that_random_filename.wav",blob);
xhr.open("POST","<url>",true);
xhr.send(fd);
}
PHP file upload_wav.php:
<?php
// get the temporary name that PHP gave to the uploaded file
$tmp_filename=$_FILES["that_random_filename.wav"]["tmp_name"];
// rename the temporary file (because PHP deletes the file as soon as it's done with it)
rename($tmp_filename,"/tmp/uploaded_audio.wav");
?>
after which you can play the file /tmp/uploaded_audio.wav.
But remember! /tmp/uploaded_audio.wav was created by the user www-data, and (by PHP default) is not readable by the user. To automate adding the appropriate permissions, append the line
chmod("/tmp/uploaded_audio.wav",0755);
to the end of the PHP (before the PHP end tag ?>).
Hope this helps.
Easiest way, if you just want to hack that code, is go in to recorderWorker.js, and hack the exportWAV() function to something like this:
function exportWAV(type){
var bufferL = mergeBuffers(recBuffersL, recLength);
var bufferR = mergeBuffers(recBuffersR, recLength);
var interleaved = interleave(bufferL, bufferR);
var dataview = encodeWAV(interleaved);
var audioBlob = new Blob([dataview], { type: type });
var xhr=new XMLHttpRequest();
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("that_random_filename.wav",audioBlob);
xhr.open("POST","<url>",true);
xhr.send(fd);
}
Then that method will save to server from inside the worker thread, rather than pushing it back to the main thread. (The complex Worker-based mechanism in RecorderJS is because a large encode should be done off-thread.)
Really, ideally, you'd just use a MediaRecorder today, and let it do the encoding, but that's a whole 'nother ball of wax.

How to read file without file input?

I'm developing an application in Javascript, which requires to read a text file and put it into a variable as input. However, I google many related questions and found that FileReader can't read file without file input because of security reason. Is there any library or dirty ways to read the content of a text file with only local path? Thanks a lot.
I think a way to do it would be to load your file with Ajax. Then you can do whatever you want with its content.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Do whatever you want here with this.responseText
}
};
xhttp.open("GET", "youtext.txt", true);
xhttp.send();
It's easier to put your file.txt or file.json to your localhost, or put it on your server.
or this link maybe can help you out
https://github.com/nwjs/nw.js/issues/3227
i understand this question that he want to read file line by line from his local path.

javascript - reading in an external local .txt file to load data into an array

I currently have javascript code (please see below) that searches an array for a month/day combination, and if it is found, assigns the name of a .jpg file (which is used for the background image of a page). Instead of hard-coding all of the data in the array, I'd like to be able to create an external .txt file with month/day codes and associated image file names, that could be read and loaded into the array. Thanks for your help!
var ourdates = ['0000','0118','0215','0530','0614','0704','0911','1111','1207']
if (ourdates.indexOf(monthday) != -1)
{
ourimage = "flag";
}
If you mean loading it from your server, that's a classic use-case for ajax, frequently combined with JSON:
var ourdates = null;
var xhr = new XMLHttpRequest();
xhr.open("GET", "/path/to/your/data");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
ourdates = JSON.parse(xhr.responseText);
// call something that uses `ourdates`
}
};
xhr.send(null)
If you mean from the user's computer, my answer here shows how to do that with the File API. Doing that requires an <input type="file"> input (or drag-and-drop event) that the user uses to grant access to the file to your script. You can't read a file from their machine without them specifically giving you access to the file.

Load a 'server-side' file with XMLHttpRequest in local html file

I want to load a json-stringified file in my javascript. The javascript reside in a html-file which I load from my local file system.
I have tried with the following code:
var xhr = new XMLHttpRequest();
xhr.open('GET', fileName, true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
if (this.status == 200) {
// get binary data as a response
var blob = this.response;
alert("Yo");
}
};
But the onload event fires only once, with the status=0, then no more happens.
I have tried to use both a full path to the file as well as a local file path like "/files/the_file.txt".
It looks like the problem is related with me trying to run the html file locally. I don't want to set-up a local server as I have seen proposed in similar posts here at so.
Anyone out there with a solution to this problem?
EDIT:
This is not what I want, but this might serve to give an example of how I almost want it. This example let the user select a file, and my script can now access the content of the selected file.
HTML:
<input type="file" id="FancyInputField" onchange="doIt();">
Javascript:
function doIt(){
var selectedFile = document.getElementById('FancyInputField').files[0];
reader = new FileReader();
reader.onload = function (e) {
var output = reader.result;
var daObject = JSON.parse(output);
}
reader.readAsText(selectedFile);
}
This also works with a local html file. (No local server)
My question stands; How do I read the file(s) with no user interaction? The files reside in a sub-folder to where the html file are located. I can with no problem load and show an image from the same sub-folder, with an <img> tag. ..So why is it so difficult to load a text file?
How do I read the file(s) with no user interaction?
You can't. Those files belong to the user, not your website. You can't choose to read them.
I can with no problem load and show an image from the same sub-folder, with an <img> tag
There is a lot of difference between displaying an image to the user, and making the content of a file available to JavaScript code written by the page author.
So why is it so difficult to load a text file?
Send someone an HTML document in an email
Enjoy the JavaScript in it scooping up files from the hard disk and sending them to Joe Evil Hacker's server
It's just basic security.
Use URL.createObjectURL(file), instead of ajax.

Access Gmail attachment from a chrome extension?

Hi I am trying to write a chrome extension which needs to read in an email attachment (plain txt). I feel this should be possible as gmail gives you a download link, however it is not a direct link does this make it impossible?
I have the following code to read a remote file which works just not for gmail:
<script>
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://remote.com/remote_file", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
lines = txtFile.responseText.split("\n"); // Will separate each line into an array
alert(allText)
}
}
}
txtFile.send(null);
</script>
Does anybody know how I can read a gmail attachment like this?
thanks
Gmail has a link to original email source ("Show Original" from the menu). Not sure if it is possible to read it programmatically, but if it is, I would try to parse original message source instead and get attachments from there (they are base64 encoded I beleive).

Categories

Resources