How to Save/Download a mp3 DataURL object using java script? - javascript

I allow the user to select a mp3 file from the local file System and then
allow to download the same file. Its for learning purpose.
<script type="text/javascript">
window.onload = function() {
document.querySelector('#musicFile').addEventListener('change', function(e){
var file = e.target.files[0];
console.log(e, file);
if(file.type.match('audio.*')) { // if its an audio file
var fReader = new FileReader();
fReader.onload = function(ev) { //onload event
var dataUrl = ev.target.result;
var downloadCon = document.querySelector('#download')
downloadCon.href = dataUrl;
};
fReader.readAsDataURL(file); //start reading the file
}
});
}
</script>
The HTML body:
<body>
<div class="controls">
<input type="file" id="musicFile">
<a id='download'href='#' download='music.mp3' class='downloadLink'>
Download File
</a>
</div>
</body>
When I click the Download File, nothing happens. Can you tell me what am I doing wrong?

You don't need to use FileReader to do that. Simply, you need to create a URLObject and make the A tag to point to it. The code for that (tested under Chrome and Firefox for Linux):
<script type="text/javascript">
window.onload = function() {
document.querySelector('#musicFile').addEventListener('change', function(e){
var file = e.target.files[0];
console.log(e, file);
if(file.type.match('audio.*')) { // if its an audio file
document.getElementById( 'download' ).href = URL.createObjectURL(file);
}
});
}
</script>
To be more specific at what I did in your code - I removed all the FileReader code and added
document.getElementById( 'download' ).href = URL.createObjectURL(file);
in it's place. I didn't touch your HTML.
Hope that helps.

Related

"change" event lags one step behind javascript

I am trying to make a very simple webpage that takes an input file and displays the contents in the console. When I try to use it, it sort of works, but is always one step behind. For example,
1) Upload "1.txt" -> Console prints ""
2) Upload "2.txt" -> Console prints contents of "1.txt"
3) Upload "3.txt" -> Console prints contents of "2.txt"
...
function readData(){
var fileholder = document.querySelector('#knotFiles');
var content = 'Empty';
var reader = new FileReader();
reader.onload = function(event){
content = event.target.result;
}
fileholder.addEventListener("input", function(event) {
var files = fileholder.files;
reader.readAsText(files[0]);
console.log(content);
}, false);
return content;
};
readData();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="" />
<title></title>
</head>
<body>
<div id="container">
<input type="file" id="knotFiles" multiple>
</div>
<script src="knot.js">
</script>
</body>
</html>
I am new to javascript and web development in general, so I apologize if this is a simple question. Thank you!
render.onload is a async function In sort content = event.target.result; will execute at the end so put console.log(content); inside render.onload for latest changes in content data
function readData(){
var fileholder = document.querySelector('#knotFiles');
var content = 'Empty';
var reader = new FileReader();
reader.onload = function(event){
content = event.target.result;
console.log(content);
}
fileholder.addEventListener("input", function(event) {
var files = fileholder.files;
reader.readAsText(files[0]);
}, false);
return content;
};
readData();
The FileReader() loads asynchronously - you are outputting the previous result because the variable content has not been updated yet before the event listener callback fires. Rewrite like this:
var fileholder = document.querySelector('#knotFiles');
fileholder.addEventListener("input", function(event) {
readData();
}, false);
function readData(){
var content = '';
var files = fileholder.files;
var reader = new FileReader();
reader.readAsText(files[0], "UTF-8"); // assumed this encoding
reader.onload = function(event){
content = event.target.result;
console.log(content);
return content;
};
}

I would like to load a list of urls to a var in any browsers' dev console (JavaScript)

I have a .txt file on my hard drive containing lots of URLs structured like this:
http://url1.com/
http://url2.com/
.
.
.
I want to load them to a var in Firefox's/Chrome's/IE's dev console so that it would be a vector of strings. I plan to visit these pages with a for loop. How can this be done?
<script>
var urls = [
'http://url1.com/',
'http://url2.com/'
];
</script>
You can generate this snippet with code or just have your file export a global variable and then load it via tags.
You can read a file via JavaScript from the page. You cannot upload a file to the developer's console.
I then modified the code bellow a bit to help you further. I added a scrape function that will help you request each URL one at a time.
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
function scrape(urls) {
url = urls.shift()
$.get(function (url) {
// get the url data here
scrape(urls);
});
}
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
scrape(reader.result.split("\n"));
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
Modified version of:
Read a local text file using Javascript
The only way di make your JavaScript aware of local files is to HTTP GET them.
So probably you have to put your file somewhere handy in the project folder and procees with an AJAX request.
var httpRequest;
function makeRequest() {
httpRequest = new XMLHttpRequest();
request.open("GET", "files/url.txt", false);
request.send(null);
saveArray(request.responseText);
}
var array = [];
saveArray(string){
array = string.split("\n")
}
You can get the contents of the file to show up in the Console with the below snippet.
var file="file://C:/FileName.txt";
function read(file)
{
var File = new XMLHttpRequest();
File.open("GET", file, false);
File.onreadystatechange = function ()
{
if(File.readyState === 4)
{
if(File.status === 200 || File.status == 0)
{
var Text = File.responseText;
console.log(Text);
}
}
}
File.send(null);
}
I found a simple but not very elegant workaround for the issue. I just copy and paste the list into a var definition. I don't have to do this often, so it is kind of okay.

How to read HTML file contents in javascript

I am sending data via ajax to post in mysql. In this context how to inlude image file contents ?
If i use like :
var formData = document.getElementById("img_file");
alert(formData.files[0]);
, i get error . Note : img_file is the id of the file dom.
Any idea about this ?
You can use javascript FileReader for this purpose. Here is a sample code demonstration.
<html>
<body>
<input type="file" id="fileinput" />
<div id="ReadResult"></div>
<script type="text/javascript">
function readSingleFile(evt) {
//Retrieve the first (and only!) File from the FileList object
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function (e) {
var contents = e.target.result;
document.getElementById("ReadResult").innerHTML = contents;
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</body>
</html>
Find more details here.
i think it may help you.
$('#image').change(function () {
$("#add").attr("disabled", true);
var img = this.files[0];
var reader = new FileReader;
reader.readAsDataURL(img);
reader.onload = function (e) {
var file = new Image;
file.src = e.target.result;
file.onload = function () {
$("#height").text(file.height);
$("#width").text(file.width);
$("#imageprev").attr("src", file.src);
$("#upld").removeAttr("disabled");
}
}
});

How to read a text file saved on my computer using javascript

I have a text file that is being updated regularly and I want to know if it is possible to read the file, line by line, with javascript and save the values in variables and then update the html page with the new values every time the page is loaded. The html page is a simple page to display information at work, not a live web page, and does not require any user input other than just navigating between the two pages. The text file is on a network drive that everyone has access to. Here is an example of what I'm trying to accomplish:
var value1;
var value2;
Read the file with javascript if possible and extract data and assign to value1 and value2.
document.getElementsByClassName("class for <p>")[0].innerHTML = value;
document.getElementsByClassName("class for another <p>")[0].innerHTML = value;
I have googled this but was not able to find anything that worked. If this is not possible with JS, any suggestions on how this can be done differently. Thanks in advance.
At first, you need to use a input[type=file] to get a File.
<input type=file id=file/>
<div id=result></div>
And then use FileReader to read file to target format, just like base64, text, buffer.
const file = document.getElementById('file').files[0]
const result = document.getElementById('result')
const reader = new FileReader
reader.addEventListener('load', () => {
result.innerHTML = reader.result
})
reader.readAsText(file, 'UTF-8')
See: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
You could use the javascript FileReader and input type="file" to read the local files in your machine. Please see the below attached code for example.
<!DOCTYPE html>
<html>
<head>
<script>
function OnFileLoad() {
var file = document.getElementById("FileReader").files[0];
var textType = /text.*/;
var fileDisplayArea = document.getElementById("FileContent");
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function (e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
}
</script>
</head>
<body>
<input type="file" id="FileReader" onchange="OnFileLoad()" />
<div id="FileContent">Your content will appear here</div>
</body>
</html>
In order to specify the file path you might need to have a server as well. I have attached a sample code here with. You can find the details regarding Specifying the file path here and issues that will happen to read file without a server here
<!DOCTYPE html>
<html>
<head>
<script>
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
var fileDisplayArea = document.getElementById("FileContent");
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText;
}
} else {
fileDisplayArea.innerText = "File not supported!"
}
}
rawFile.send(null);
}
readTextFile("file:///C:/Users/t0423/Desktop/test.js")
</script>
</head>
<body>
<div id="FileContent">Your content will appear here</div>
</body>
</html>

HTML5 File Handeling in JavaScript?

What techniques are used to load a file (ASCII or Binary) into a variable (var file = "text";) in JavaScript?
You want to use the new HTML5 File API and XMLHttpRequest 2.
You can listen to files being either selected via a file input or drag & dropped to the browser. Let's talk about the input[type="file"] way.
<input type="file">
Let's listen for files being selected.
var input; // let input be our file input
input.onchange = function (e) {
var files = input.files || [];
var file = files[0];
if (file) {
uploadFile(file);
}
};
What you need to create a real multipart file upload request is a FormData object. This object is a representation of the body of your HTTP POST request.
var uploadFile = function (file) {
var data = new FormData();
data.append('filename', file);
// create a HTTP POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', './script.php', true);
xhr.send(data);
xhr.onloadend = function () {
// code to be executed when the upload finishes
};
};
You can also monitor the upload progress.
xhr.upload.onprogress = function (e) {
var percentage = 100 * e.loaded / e.total;
};
Ask if you need any clarification.
If you want to use the new HTML5 way this is how I did it... keep in mind that I made a method called File() and this is not a true HTML5 method its a wrapper to it... this might be changed in the future so beware (maybe rename it).
HTML:
<html>
<body>
<input type="file" id="files" name="file"/>
<button onclick="load()">Load File</button><br /><br />
<div id="content"></div>
<script>
function load() {
var fileObj = document.getElementById("files");
var fp = new File(fileObj);
fp.read(callback);
}
function callback(text) {
var content = document.getElementById("content");
content.innerHTML = text;
}
</script>
</body>
</html>
JavaScript:
function File(name) {
this.name = document.getElementById(name) ? document.getElementById(name).files : name.files ? name.files : name;
}
// Reads the file from the browser
File.prototype.read = function(callback) {
var files = this.name;
if (!files.length) {
alert('Please select a file!?');
return;
}
var file = files[0];
var reader = new FileReader();
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
callback(evt.target.result);
}
};
var data = file.slice(0, file.size);
reader.readAsBinaryString(data);
}
Have the JavaScript being generated inside a PHP or Rails (or whatever you use server-side) and include the file.
<?php
$my_string = file_get_contents('/path/to/file.txt');
?>
<script>
var my_js_file_string = "<?php echo $my_string; ?>";
...
document.write(my_js_file_string);
</script>

Categories