How to read file contents using javascript?

I have an input type="file" button. After selecting the file, I have to read the contents of the file using javascript. Is it possible to read / receive the contents of the selected file using javascript or ajax?

+4
source share
8 answers

With AJAX, you can read the downloaded file, but with pure javascript it is not possible, because javascript works on the client side, not on the server side.

if you are going to use jquery since an Ajax call might be like this

 $.ajax({ url: "test.html", context: document.body, success: function(){ $(this).addClass("done"); } }); 
+7
source

You are all mistaken. Maybe. With the new file API, you can read files before sending them to the server. However, it is not available in all browsers.

Check out this example. Try opening a text file, for example.

http://development.zeta-two.com/stable/file-api/file.html

Edit: even though the question says “uploaded file”, I interpret it as “download file”. Otherwise, it does not make sense.

+9
source

Reading files on the client side is difficult:

How to read and write to a file using JavaScript

Read local file

Local file access using javascript

If you are not trying to do this using local javascript:

Access local files with local Javascript

Or server side javascript:

http://en.wikipedia.org/wiki/Server-side_JavaScript

Alternatively, you can force the user to install an ActiveX object:

http://4umi.com/web/javascript/fileread.php

+3
source

you cannot do this directly with javascript. You can send the file to the server and then use ajax to retrieve the content.

0
source

Javascript is not intended to access the computer on which it is running. This is so that the jug code cannot read the user's hard drive. However, you could use iframes.

0
source

This cannot be done in java script. See Local file access using javascript

I agree with DoXicK above. You can publish the file first on the server, and then you can use Ajax to read it.

0
source

This is not entirely impossible.

The browser typically runs Javascript (JavaScript Engine) in an isolated environment.

This way you can use Windows Scripting Host or Internet Explorer in a trusted environment and use FileSystemObject

or use

Or upload the file to your server and use the XMLHttpRequest object (in other words, Ajax)

0
source

For IE, use FileSystemObject (which is found on all Windows systems).

For Firefox:

 var file = Components.classes["@mozilla.org/file/local;1"]. createInstance(Components.interfaces.nsILocalFile); file.initWithPath("/home"); 

See https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO

To see these methods and others that you use, check out the TiddlyWiki app to see how it works in all major browsers.

0
source

Source: https://habr.com/ru/post/1345667/


All Articles