Can javascript display text of any external file with any extension? [duplicate] - javascript

This question already has answers here:
Local file access with JavaScript
(14 answers)
How to read a text file containing html without using input type file in JavaScript?
(2 answers)
Closed 3 years ago.
Lets consider that I have a text file named text.txt. So, now I made a file named showtext.html in which I have to write javascript such that it can display the text present in text.txt. I assume it would be like :
Text ( text.txt )
Show me up !
HTML ( showtext.html )
<!DOCTYPE html>
<html>
<body>
<script>
var src = "text.txt";
document.write( value.get( src ) );
</body>
</html>
Output of showtext.html
Show me up !
In, the above function the value.get() gets and then writes the value of the text.txt. So, can javascript really do such ? How can I make the value.get() ? Will it support only .txt extension or can support any custom extension ? Or this can only be done with PHP ?

"Local" means "all client, no server" :) If you don't have a server, you can't use things like fetch() (as far as I know, security restrictions prevent that). But you can read a file from the local computer on the client as long as the user selects the file themselves. You can't just read any arbitrary file from the client's computer (again, for security reasons).
If you're okay with letting the user select the file, look into the FileReader API.
HTML:
<input type='file' id='fileSelector' />
JS:
const fileInput = document.getElementById('fileSelector');
fileInput.addEventListener('change', event => {
const file = event.target.files[0];
const reader = new FileReader();
reader.addEventListener('load', readEvent => {
// In here, readEvent.target.result will have the text of the file for you to work with.
});
reader.readAsText(file);
});

Related

how make the file path dynamic [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 6 years ago.
Hi I wrote the below Java code to email a file as attachement. It works fine if I provide a sample filepath. But, I want it to take the file path browsed by the user in the Front End
//code to attach the file
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart.setText(sb.toString());
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
//String filename = filePath;
String filename = "C:/Users/S.Mandava/Documents/ContactusAction.java";
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(messageBodyPart2);
msg.setContent(multipart);
System.out.println("Attaching the file");
Transport.send(msg);
Form example,
I want the system to take the file path uploaded in the below form when the user clicks on submit and the file should be sent as an attachment in an email
<form >
<input type ="file"/ id="multiple_files" name="multiple_files" multiple><br/>
<button>Submit</button>
</form>
How do I do it? I want to use JSP and JavaScript on the Front End and Java on the Back End. I am having difficulty in getting the file path.
As #Rishal_dev_singh said, search for examples, Google is your friend... What you do is an InputStream, you don't define a path

How to programmatically select local file in input type="file"

I want read a local txt file with javascript on chrome browser. So, I use <input type="file" .../> and when I select any txt file, I read it. But I dont want select file. I need to load the file with the file path. How is this possible?
Thanks
You can't do this. This is obviously because of security implications: imagine if any website you visit could read your FileZilla preferences file, which contains all your unencrypted FTP passwords? I bet you wouldn't like that.
You have to obtain a File reference (e.g. from an event handler) before being able to manipulate it. More info.
if you want to read file data opened from file dialog:
function readFile(){
var t = document.getElementById("file")
var o = new FileReader();
o.onload = function(t) {
console.log(t.target.result);
}
o.readAsText(t.files[0]);
}
edit: you can't just open files without selecting it first

Need Access to Local Text File via JavaScript

I am working on a project which must be self contained and able to run without an internet connection. It's is for video presentations and I need to import a .txt file which includes chapters and loop information such as Chapter Title, Looping point and chapter end point (both in frames). However, there is no client-side include script to include a text file.
What would be the best way for me to store or access a local text file so that I can iterate over it and build my chapters object? HTML5 local storage? Hacking by including a hidden iframe that loads the text file then grab that body content via JavaScript? Any help on this issue would be greatly appreciated.
Thanks!
For your question "Need Access to Local Text File via JavaScript" is very similar to this question here: Local file access with javascript
The Answer is there really isn't a good way to access a local file if you are using javascript in a browser. If its just a text file on the same machine without a http/webserver you may run into some problems, as in javascript the ability to read a local file is disabled by default in most browsers. In chrome you can disable this security-feature by adding the following flag when starting the browser from command-line.
--disable-web-security
If your data is structured json, xml, csv, you can bring it in using an AJAX call if the file is hosted on a server accessible with HTTP. Without using an http ajax call, another possible solution as mentioned in the question link above:
Just an update of the HTML5 features http://www.html5rocks.com/en/tutorials/file/dndfiles/
This excellent article will explain en detail the local file access in
Javascript. Summary from the mentioned article:
The spec provides several interfaces for accessing files from a
'local' filesystem:
File - an individual file; provides readonly information such as name,
file size, mimetype, and a reference to the file handle. FileList - an
array-like sequence of File objects. (Think or dragging a directory of files from the desktop). Blob -
Allows for slicing a file into byte ranges.
-- #Horst Walter
As shown below you can have a "file upload" input selection, and simply have your file path as a default option for the input"
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
output.push('<li><strong>', escape(f.name), '</strong> (', f.type || 'n/a', ') - ',
f.size, ' bytes, last modified: ',
f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
'</li>');
}
document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
You can use AJAX to read the text file.
with javascript you can't edited, you can only read it.
an example will be :
1- create a text file "page.txt"
2- create a html page with this code
<!DOCTYPE html>
<html>
<body>
<script>
text = new XMLHttpRequest();
text.open("GET","page.txt",false);
text.onload = function(){
document.write(text.responseText);
}
text.send();
</script>
</body>
</html>

How To get the full path of the folder selected [duplicate]

This question already has answers here:
How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?
(14 answers)
Closed 9 years ago.
I have created <input type="file" name="files" id="fld1" webkitdirectory > in an html file.
i can get the files using
var imageFiles = document.getElementById("fld1"),
filesLength = imageFiles.files.length;
for (var i = 0; i < filesLength; i++) {
alert(imageFiles.files[i].name);
}
How can i get the full path of the directory selected in javascript . please help
I want to show all the image files present in any folder using jquery slider. i can get the name of the files present in that folder but i cannot get the full path of the folder. how can i get it.
i have done this to get the file path but it only worked in IE
<script language="JavaScript">
function GetDirectory() {
strFile = document.MyForm.MyFile.value;
intPos = strFile.lastIndexOf("\\");
strDirectory = strFile.substring(0, intPos);
alert(strFile + '\n\n' + strDirectory);
return false;
}
</script>
For obvious security reasons you cannot do that. Browsers won't allow you to access and explore the file system of the client computers using javascript. Some browsers will simply return some fake path to the file.
Check File API documentation, the File section gives details about the File object.
Quoting from the doc:
The name of the file; on getting, this must return the name of the
file as a string. There are numerous file name variations on different
systems; this is merely the name of the file, without path
information. On getting, if user agents cannot make this information
available, they must return the empty string.

How to use input type file in phonegap? [duplicate]

This question already has answers here:
How to upload file with Phonegap and JqueryMobile?
(2 answers)
Closed 3 years ago.
How to use html file attribute in phonegap ? so that i can browse any .txt file from my android device and upload it to the server??
I read file transfer method in phonegap documentation but according to that it is possible to upload files to the server only through url.But is it possible in normal way like :
<input type=file /><button>upload</button>
input type="file" accept="image/*" doesn't work in phone gap? i looked at this link but that says only for images .
But how to upload the text files ?
Any help??
Can anybody answer this?
You can't use input file on Phonegap. It's not supported. You need make something like this:
function uploadDatabase(callback) {
// file.entry accessible from global scope; see other tutorial
var filepath = file.entry.fullPath,
uploadOptions = new FileUploadOptions(),
transfer = new FileTransfer(),
endpoint = "http://facepath.com/payload";
uploadOptions.fileKey = "db";
uploadOptions.fileName = "database.db";
uploadOptions.mimeType = "text/plain";
transfer.upload(filepath, endpoint, transferComplete,
transferError, uploadOptions);
}
in mime type put the type of file
I wrote this answer "You can't use input file on Phonegap. It's not supported.". Check the solution on https://stackoverflow.com/a/13862151/1853864

Categories

Resources