Using jQuery, is it possible to read from file.txt and output to a paragraph tag not on the server?
3 answers
An example of using the File API:
document.getElementById('file').onchange = function(event) { let file = event.target.files[0]; if (!file) return; let reader = new FileReader(); reader.onload = function(event) { document.getElementById('filecontent').innerText = event.target.result; } reader.readAsText(file); } <input type="file" id="file"></input> <p id="filecontent"></p> - but simply without input you can not display? - user33274
- oneWithout
inputbrowser does not have access to the files. Otherwise, any site could read any of your files - Nick - @ MaximLensky It is impossible. For security reasons, FileReader can only read files explicitly selected by the user. - Yaant
|
You can use the File API . But only in the case when the user himself chose this file from the computer using input: file.
- Check that FileAPI is supported by the browser.
- Get File object from input: file.
- Read the file using FileReader in line
- Add this line as text in the paragraph.
Here is a good article on this topic.
- The file reader does not work locally, I read this article already - user33274
- Then no way. Otherwise, it would be possible to view his files unnoticed by the user - user3127286
- @ MaksimLensky why not work? Works, see an example in my answer. - Yaant pm
|
For example:
$.ajax({ url : "file.txt", dataType: "text", success : function (data) { $("p.text").html(data); } }); - 2re-read the question ... on ajax this and first-graders can ... - user33274
- it is written ... not on the server, minusovl not me - user33274
|