Load text from local .txt file into html textarea using JavaScript
You can use the File and FileReader objects to read local files.
You can use an input element with type="file" to allow the user to select a file.
<input id="myFile" type="file"/>
<textarea id="myTextArea" rows="4" columns="20"></textArea>
After the user has selected a file, you can get the File object from the input element. For example...
var file = document.getElementById("myFile").files[0];
You can then use a FileReader object to read the file into the text area. For example...
var reader = new FileReader();
reader.onload = function (e) {
var textArea = document.getElementById("myTextArea");
textArea.value = e.target.result;
};
reader.readAsText(file);
Loading .txt file into textarea Javascript?
Thanks everyone. Javascript didn't work for me. I changed to PHP and it's working very well.
<!DOCTYPE HTML>
<html>
<head>
<title>textbox</title>
</head>
<body>
<form action="process.php" method="post">
<input type="text" name="name" />
<input type="submit" />
</form>
</body>
</html>
Process.php
<textarea name="text" rows="20" cols="70">
<?php $name = $_POST["name"]; echo file_get_contents("$name");?>
</textarea>
loading a text file into the correct textbox in html
I'm not sure if this is what you're looking for, but here goes:
<table>
<tr><td>Text to Save:</td></tr>
<tr>
<td colspan="3">
<textarea class="inputTextToSave" cols="80" rows="5"></textarea>
<textarea class="inputTextToSave" cols="80" rows="5"></textarea>
</td>
</tr>
<tr>
<td>Filename to Save As:</td>
<td><input id="inputFileNameToSaveAs"/></td>
<td><button onclick="saveTextAsFile()">Save Text to File</button></td>
</tr>
<tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad"></td>
<td><button onclick="loadFileAsText()">Load Selected File</button>
<td>
</tr>
</table>
Here I add a second TextArea and change id for class to select all TextArea by className.
var delim = "[^~^]"
function getAllTextBoxesText() {
var allText = "";
var textBoxes = document.getElementsByClassName("inputTextToSave");
for (var i = 0; i < textBoxes.length; i++) {
allText += textBoxes[i].value + delim;
}
return allText;
}
function splitTextBox(allText) {
var textBoxesTexts = allText.split(delim);
var textBoxes = document.getElementsByClassName("inputTextToSave");
for (var i = 0; i < textBoxes.length; i++) {
if (i >= textBoxesTexts.length)
break;
textBoxes[i].value = textBoxesTexts[i];
}
}
function saveTextAsFile() {
var textToSave = getAllTextBoxesText();
var textToSaveAsBlob = new Blob([textToSave], { type: "text/plain" });
var textToSaveAsURL = window.URL.createObjectURL(textToSaveAsBlob);
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
downloadLink.href = textToSaveAsURL;
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
downloadLink.click();
}
function destroyClickedElement(event) {
document.body.removeChild(event.target);
}
function loadFileAsText() {
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function (fileLoadedEvent) {
var textFromFileLoaded = fileLoadedEvent.target.result;
splitTextBox(textFromFileLoaded);
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
The idea is join all textarea's texts in one string and later, split them. To do that, I use a delimiter. You must use some delimiter that you know won't appear in your text. Usually, a non printable character like ¶ (0xB6 in hexadecimal) may be useful.
With this idea, I use getAllTextBoxesText function to join all textarea's texts in a single string. This is the text to save with your original save function.
For the load part, we do the same: splitTextBox function only splits the text using the delimiter and set each part in one textarea. I use this function in your loadFileAsText, after get the loaded text content.
You can test here: https://jsfiddle.net/pyv5djbe/
How to load data from a .txt file into a textarea
Since you are working with a textarea
, you need to specify the value rather than the html.
Change:
$('fillText').html(data.replace('n',''));
To:
$('#fillText').val(data.replace('n',''));
how to Load Text file into HTML, inside textarea tag?
You can use PHP to load files from the user's computer. Here is an example.
form.html
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if(isset($_POST["submit"])) {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
header("Location: http://example.com/displaymessage.php?filename=" + basename( $_FILES["fileToUpload"]["name"]));
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
displaymessage.php
<?php
$file = $_GET['filename'];
?>
<script>
var client = new XMLHttpRequest();
client.open('GET', '/uploads/<?=$file?>');
client.onreadystatechange = function() {
document.getElementById("#textbox").value = client.responseText;
}
client.send();
</script>
Make sure to change #textbox
, to the ID of the textarea tag. (e.g. <textarea id="foo">
)
NOTE: I just came up with half of this code, and I am not sure if it will work
Loading a text file into a textarea
Use the read(...) and write(...) methods that are suppoorted by all Swing text components. Simple example:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
class TextAreaLoad
{
public static void main(String a[])
{
final JTextArea edit = new JTextArea(10, 60);
edit.setText("one\ntwo\nthree");
edit.append("\nfour\nfive");
JButton read = new JButton("Read TextAreaLoad.txt");
read.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileReader reader = new FileReader( "TextAreaLoad.txt" );
BufferedReader br = new BufferedReader(reader);
edit.read( br, null );
br.close();
edit.requestFocus();
}
catch(Exception e2) { System.out.println(e2); }
}
});
JButton write = new JButton("Write TextAreaLoad.txt");
write.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
FileWriter writer = new FileWriter( "TextAreaLoad.txt" );
BufferedWriter bw = new BufferedWriter( writer );
edit.write( bw );
bw.close();
edit.setText("");
edit.requestFocus();
}
catch(Exception e2) {}
}
});
JFrame frame = new JFrame("TextArea Load");
frame.getContentPane().add( new JScrollPane(edit), BorderLayout.NORTH );
frame.getContentPane().add(read, BorderLayout.WEST);
frame.getContentPane().add(write, BorderLayout.EAST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
Load Textfile via Drag and Drop on Textarea
You are passing the file to dropfile
function.
var file = e.dataTransfer.files[0];
dropfile(file);
in dropfile
function you are consuming it wrong.
reader.readAsText(input.files[0],"UTF-8");
you should change the line to
reader.readAsText(input,"UTF-8");
Try the below snippet.
function dropfile(file) {
var reader = new FileReader();
reader.onload = function(e) {
notepad.value = e.target.result;
};
reader.readAsText(file, "UTF-8");
}
notepad.ondrop = function(e) {
e.preventDefault();
var file = e.dataTransfer.files[0];
dropfile(file);
};
html,
body {
height: 100%;
padding: 0;
margin: 0;
}
#notepad {
position: absolute;
top: 0;
left: 0;
bottom: 0;
border: 0;
padding: 1em;
width: calc(100vw - 2em);
resize: none;
}
#notepad:focus {
outline: 0;
}
<textarea
id="notepad"
placeholder="drag and drop your .txt file"
></textarea>
Related Topics
Java Outofmemoryerror Strange Behaviour
How to Bind an Object List with Thymeleaf
Why Can Final Object Be Modified
How to Get a Spring Bean in a Servlet Filter
Does Java Support Inner/Local/Sub Methods
Jpa: What Is the Proper Pattern for Iterating Over Large Result Sets
Registering Multiple Keystores in Jvm
How to Copy Java Collections List
Springboot - Making Jar Files - No Auto Configuration Classes Found in Meta-Inf/Spring.Factories
What Does Class<> Mean in Java
What Java 8 Stream.Collect Equivalents Are Available in the Standard Kotlin Library
Difference Between @Onetomany and @Elementcollection
Stringutils.Isblank() VS String.Isempty()
Default Fetch Type for One-To-One, Many-To-One and One-To-Many in Hibernate