Javascript: variable file from string - javascript

Hopefully this is a pretty simple question for those who know javascript but I couldn't figure it out. Basically I have a save file dialog box created with this:
<div>
<input type="file" id="file" onchange="loadFile(this)">
</div>
It is linked to the "loadfile" function shown below:
function loadFile(input) {
var file = input.files[0]
var url = file.urn || file.name;
ID3.loadTags(url, function() {showTags(url);}, {tags: ["title","artist","album","picture"],dataReader: FileAPIReader(file)});
}
I am trying to replace the line
var file = input.files[0]
to be a file from a string (specified path) instead of relying on the file browser dialog. I have tried something like this:
var file = files("song.mp3")
but the resulting function will not work. I am guessing that my variable file isn't of the right type. How do I get it to be the same type as the selected file from the file dialog box?
Thanks in advance!
PS:
I am trying to link my script to a path on the server not the client.

If you want to access data from a website, then use the XMLHttpRequest object instead of the Files API.

Related

Choosing the path of a file directly in script?

Alright, so here's my little problem.
I am trying to read a file directly from the script in JavaScript, but I have no idea how.
In order to get my file in a variable, I use this:
function readSingleFile(e) {
var file = e.target.files[0];
if (!file)
return;
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
};
reader.readAsText(file);}
document.getElementById('file-input')
.addEventListener('change', readSingleFile, false);
with this HTML:
<input type="file" id="file-input" />
The main idea is, how do I choose the path of 'file' variable directly in script? Thank you so much!
The main idea is, how do I choose the path of 'file' variable directly in script?
You can't. It would be a security violation to allow JavaScript code to read any file it wanted from the user's system. That's why if you look at the "path" you get from the input type="file", you'll see a fake path (but likely a real filename) like (on Windows) C:\fakepath\realFileName.txt.
This question is closely related to, though perhaps not quite a duplicate of, Dynamically set value of a file input.

get file object using full path

is there a way to get a file object using the directory full path of the file itself? this piece of code wont work:
var file1 = new File("D:\\path\\to\\file\\file.txt");
I need to get the file object since I have a function that has a file object as its parameter.
bryan
That would be very tragic if browsers could suddenly start accessing users' file systems without their permission.
I would suggest using <input type="file">. This way the user chooses which file they will allow the browser to access.
I would suggest you to use: <input type="file" id="fileUpload"> and get the file name using
$('input[type=file]').change(function () {
console.log(this.files[0])
});

Get filename from input file in Javascript

I have noticed that bootstrap is able to parse out and display the top level filename from a file input field when the user selects a file.
<input type="file" id="exampleFile">
JSFiddle: http://jsfiddle.net/na4j7n6y/
My question: Is this functionality exposed for me to use in my own javascript code? Or do I have to parse out the filename once again using my own technique?
I have tried retrieving the filename like so:
$('#exampleFile').val()
// Resolves to 'C:\fakepath\FILENAME' instead of 'FILENAME'
Well, bootstrap is a framework based on html, css and javascript. The javascript part of this framework uses jQuery and not a own library. Then you could try to solve it using a regex with javascript/jquery, for sample:
var fullPath = $("#exampleFile").val();
var filename = fullPath.replace(/^.*[\\\/]/, '');
Take a look here:
http://jsfiddle.net/na4j7n6y/1/
How to get the file name from a full path using JavaScript?
Check this JSFiddle to reference the filepath displayed.
http://jsfiddle.net/67y9tpd4/
HTML
<div id="write"><button type="button" onclick="getAfilepath()">Print Filepath</button></div>
JS
function getAfilepath(){
var afilepath = document.getElementById("uploadFile").value;
document.getElementById("write").innerHTML=afilepath;
}

javascript read file object unknown id

Is it possible to use javascript File API to read a file object of unknown id?
I use a custom file upload form in which the code doesn't have an input element. It uses plupload.js API and I can't determine how to access to the contents of file object.
For example if the code had something like the line 1, I could access the contents of file object using the code of line 2
input type="file" id="data"
var finput = document.getElementById("data"); var f = finput.files[0];
I tried something like document.files[0] but it doesn't work. Do you know something similar?
Instead of document.files[0], try document.querySelectorAll('input[type="file"]')[0].
function demo(){
var inpts=document.querySelectorAll('input[type="file"]');
alert(inpts[0].className);
}
<input type="file" class="file_input_a"><br>
<input type="file" class="file_input_b"><br>
<input type="file" class="file_input_b"><br>
<button onclick="demo()">Demo</button>
The above example echo's the classname of file-input 0 (to simply show we have a reference to it).
From here on you want to grab (for example) first file (from the first found input-element):
var f = inpts[0].files[0];
PS: there is a lot of good related info in my answer linked here.

Read and display the text file contents upon click of button using Javascript

On click of a button called result, I want to read and display a text file (which is present in my local drive location say: C:\test.txt) using Javascript function and display the test.txt file contents in a HTML text area.
I am new to Javascript,can anyone suggest the code for Javascript function to read and display the contents of .txt file?
An Ajax request to a local file will fail for security reasons.
Imagine a website that accesses a file on your computer like you ask, but without letting you know, and sends the content to a hacker. You would not want that, and browser makers took care of that to protect your security!
To read the content of a file located on your hard drive, you would need to have a <input type="file"> and let the user select the file himself. You don't need to upload it. You can do it this way :
<input type="file" onchange="onFileSelected(event)">
<textarea id="result"></textarea>
function onFileSelected(event) {
var selectedFile = event.target.files[0];
var reader = new FileReader();
var result = document.getElementById("result");
reader.onload = function(event) {
result.innerHTML = event.target.result;
};
reader.readAsText(selectedFile);
}
JS Fiddle
Using $.ajax() function: http://api.jquery.com/jQuery.ajax/
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
As You've mentionned HTML, I assume you want to do this in a browser; Well the only way to access a local file in a browser is by using the File API, and the file can only be obtained via a user's manipulation such selecting a file in an <input type='file'> element, or drag&dropping a file in your page.
We could achieve this by, I should say, creating a virtual file!
Storing the contents of the text file into a Javascript string variable. However, one should consider all new lines and other special symbols\characters and etc.!
We than can markup a script tag in our HTML to load that *.js Javascript like this:
<script src="my_virtual_file.js"></script>
The only difference here is that a text file that could contain:
Goodnight moon
Follow the white rabbit
In a Javascript script string variable should look like this:
var my_virtual_file = "Goodnight moon\nFollow the white rabbit";
Later on, you can access this variable and treat it as you wish...
A programming language like Javascript that follows standards like ECMAScript, gives you a wide range of capabilities to treat and convert data from one type into another.
Once you have your Javascript script loaded, you can then access that variable by any button in your HTML by assigning a function call on its onclick attribute like this:
<button onclick="MyVirtualFile()"></button>
And ofcourse, you just add a script tag to your HTML, like this:
<script>
functiion MyVirtualFile(){
alert(my_virtual_file);
};
</script>
... or your may just create and import another Javascript script containing that same function, under your desire.
If you are concerned about how much information you can store into a Javascript string variable, just take a look at this interesting (and old as this one :D) SO thread.
Lets see if this snippet works :):
var my_virtual_file = "Goodnight moon\nFollow the white rabbit"
function MyVirtualFile(){
alert(my_virtual_file);
// Do anything else with your virtual file
};
<!DOCTYPE html>
<html>
<head>
<script src="my_virtual_file.js">
</script>
</head>
<body>
<h1>HTML Javascript virtual file</h1>
<button onclick="MyVirtualFile()">Alert my_virtual_file</button>
</body>
</html>
You can programatically access and dynamically change the contents of your Javascript script, but you should remind that you need to reload your HTML so the browser can load the new contents.
On your filesystem, you can just treat this *.js as a *.txt file, and just change its contents keeping in mind the Javacript.

Categories