I'm just trying on the task, file manipulation system using java script. As I was referred from W3C File API( https://www.w3.org/TR/FileAPI/ ), we can only read local files like
var file = "test.txt";
function readTextFile(file) {
var readFile;
if(window.XMLHttpRequest){
// for new browsers
readFile = new XMLHttpRequest();
}else{
//for old browsers like IE5 or IE6
readFile = new ActiveXObject("Microsoft.XMLHTTP");
}
readFile.open("GET", file, true);
readFile.onreadystatechange = function() {
if(readFile.readyState === 4) {
if(readFile.status === 200 || readFile.status == 0) {
//text will be displayed that read from the file
console.log(readFile.responseText);
}
}
}
readFile.send(null);
}
but it looks there is no options to write on file without server. I was tried to fetch solutions from the websites like http://www.stackoverflow.com/, the study says almost there is no possibilities.
For an example what I got is
from https://gist.github.com/Arahnoid/9925725
It shows error "TypeError: file.open is not a function."
So my question is, Is there any possible to file manipulations(asking only about Write file) for local files without using server-side scripting or is any extensions like available?
We can do file manipulations using server scripting languages such as PHP, Node.js.
Thanks in advance.
In your code, it's not reading from the local file (test.txt), it's sending Ajax GET request to server and read file in server side.
To read local file (files that stored in machine where browser is installed), you need to use FileAPI, which is not used in current code.
To write file to local, it's impossible to write it directly using JavaScript. Otherwise, it would be a huge security vulnerability. However, you can generate a URL from File object, and use that URL as the href attribute of <a> tag, so that user can download and "write to local" manually.
Here is a code snippet to read & "write" local file:
var inputElement = document.getElementById("input");
var reader = new FileReader();
var downloadLink = document.getElementById('downloadLink');
reader.onloadend = function(){
console.log(reader.result);
}
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
var fileSelected = this.files[0]; /* now you can work with the file list */
reader.readAsBinaryString(fileSelected);
downloadLink.href = window.URL.createObjectURL(fileSelected);
}
<input type="file" id="input">
<a id="downloadLink" download>Download</a>
Related
For minimal example, I have
Host: 111.222.111.123
Username: user_name
Password: pass_word
File to upload is selected with HTML input element
I can upload the file manually to the target directory on the server with a client like FileZilla.
The target directory is where the file should be uploaded. Its location on the Internet is https://nameofsite/targetdir/, so the file should be reachable on the internet for anyone as https://nameofsite/targetdir/1.html.
But is it possible to upload the file to the server with javascript?
I tried this example taking to account #mcrdy455's answer, but anyway it's not clear what the FtpConnection is:
<input id="fileForUpload" type=file onchange="upload()">
<div id="fileContents"></div>
<script>
function upload() {
var file = document.getElementById("fileForUpload").files[0];
if (file) {
var reader = new FileReader();
reader.readAsText(file, "UTF-8");
reader.onload = function (evt) {
document.getElementById("fileContents").innerHTML = evt.target.result;
var ftp = new FtpConnection("ftp://111.222.111.123/");
ftp.login("user_name", "pass_word");
ftp.put(file, "1.html");
ftp.close();
file.close();
}
}
}
</script>
Uncaught ReferenceError: FtpConnection is not defined
After searching on the Internet, I'm still not sure what project FtpConnection belongs to. Other examples use URLs instead of IP addresses (111.222.111.123).
E.g. Ftp.createCORSRequest('POST', "http://www.ftpjs.xyz/upload.aspx") in this one. I would like not to complicate things (with CORS) and use the 111.222.111.123 address.
If FileZilla can do the job, why couldn't javascript do it? How?
The JavaScript code can NOT access files from your filesystem, use an input type file, and read the file through the FileReader: You can fine more info on how to do this here, Once you have the correct file/blob object you code should work
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.
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.
I have a standard folder structure for a web app.
css
js
img
asetts
lib
index.html
Inside my assets folder I have a bunch of plain text files and I would like to first be able to list the filenames using Javascript, so I can store the URI's in the model, and read from them later on the in the application. I want all of this happening client side.
(Client-side) JavaScript does not have access to the file system like that.
This is not possible without some kind of browser plugin.
You can read the textfiles in the local folder.
function read()
{
var xHR = new XMLHttpRequest();
//replace textfile_url with the relative url of your text file
xHR.open("GET", "textfile_url", true);
xHR.onreadystatechange = function ()
{
if(xHR.readyState === 4)
{
//all your text is in the next line
var text = xHR.responseText;
}
}
xHR.send();
}
Based on research, I've found tutorials, such as this one from Eric Bidelman, that go into FileReader usage. Instead of local files, these tutorials use files provided by the user. Modifying these examples to try and display local files were not successful.
After some research I've found that most browsers by default do not allow access to local files [1]. Some recommend using unsafe modes for testing, but that's not what I'm looking for as that would apply to only my testing [2].
Currently I allow the download of log files. My goal here with FileReader was to provide a way to view the files as well. Is there a way to achieve this? I'm coming up with blanks and have almost resigned to only allowing downloads instead of adding viewing. The following is example code of local file reading. This code fails since 'logpath' is not of type blob. I believe my question doesn't really require code, but I provided an example anyway.
HTML Code
<select name="loglist" id="loglist" onchange="run()" size="2">
<option>stack1.log</option>
<option>stack2.log</option>
</select>
Javascript
function run() {
var reader = new FileReader();
log = document.getElementById( "loglist" ).value;
var logdir = "/var/log/";
var logpath = logdir.concat(log);
reader.onload = function() {
logtext = reader.result;
alert(logtext);
}
reader.readAsText(logpath);
}
There is no way for JavaScript, embedded in a webpage, to access files on the user's local system other than through the File API when the user selects the file using a file input. It is not possible for the page to supply the file name to be opened.
var inp = document.querySelector("input");
inp.addEventListener("change", show);
function show(e) {
var f = this.files[0];
var r = new FileReader();
r.addEventListener("load", display);
r.readAsText(f);
function display(e) {
document.body.appendChild(
document.createTextNode(
e.target.result
)
);
}
}
<input type="file" id="input">