Jump to content

Display local or web txt file in a textarea (JSON import)


SerenityNetworks

Recommended Posts

I'm using the following button to identify a txt file for import.

<input type="file" id="theDataFile" single class="smallStyle"/>

Then I use the following code to parse the contents of the txt file into a textarea.

	var control = document.getElementById("theDataFile");	control.addEventListener("change", function(event) 		{	    // When the control has changed, there are new files	    var i = 0,	        files = control.files,	        len = files.length;	    for (; i < len; i++) {	        //alert("Filename: " + files[i].name + "  | Type: " + files[i].type + "  |  Size: " + files[i].size + " bytes");	        var url2 = files[i].name;	    }	var xmlhttp = new XMLHttpRequest();	xmlhttp.onreadystatechange = function() {	    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {	        var myArr = JSON.parse(xmlhttp.responseText);	        myFunction(myArr);	    }	}	xmlhttp.open("GET", url2, true);	xmlhttp.send();	function myFunction(arr) {	    var out = "";	    var i;	    for(i = 0; i < arr.length; i++) {	    	out += '' + arr[i].time + ' | ' + arr[i].text + ' | ' + arr[i].x + ' | ';	        //out += '<tr><td>' + arr[i].time + '</td><td>' + arr[i].text + '</td><td>' + arr[i].x + '</td></tr>';	    }	    	document.getElementById("id01").innerHTML = out;	    	//document.getElementById("id01").innerHTML = '<table><tr><th>This</th><th>That</th><th>Another</th></tr>' + out + '</table>';		}	}	, false);

This all works fine with the limitations that:

  • I'm using XAMMP as a Apache server on my laptop.
  • The txt files are on my laptop.
  • The txt files are in the same directory as the html page loading the txt file.

But I would like to place the html page on my hosted server. I would prefer to load local txt files into the textarea, but I'm not seeing how to do it. If loading local txt files is not possible then I could upload the files to my server, but then I need a way to select the file for display in the textarea. I do not know how to do that either.

 

Any help would be greatly appreciated, especially with being able to simply have a local file display in the textarea.

 

Thank you in advance,

Andrew

Link to comment
Share on other sites

Ugh. I've already done lots of work with this and have functionality built around it. I'd rather not start over. I'd greatly prefer a way to just get what I have displaying a local file.

Link to comment
Share on other sites

The FileReader API is the way for Javascript to access local files on the user's hard drive. You've already learned that sending ajax requests for local files doesn't work online, so it's unfortunate that you've spent time proceeding in that direction. The alternative, like you've suggested, is to upload the file to the server and then have the server return the data. If you want to upload the file with ajax then that's some more research into things similar to FileReader (you actually use FileReader as part of the ajax upload process), or else you can do a normal form upload and then refresh the page with the data filled in.

Link to comment
Share on other sites

Thanks. Yes, bummer. So let's go with uploading a file and displaying it. I've already tested the upload function with the following two pages.

<!DOCTYPE html><html><body><form action="upload.php" method="post" enctype="multipart/form-data">    Select lane file to upload:    <input type="file" name="fileToUpload" id="fileToUpload">    <input type="submit" value="Lane File" name="submit"></form></body></html>

Then...

<?php$target_dir = "/home3/fagancon/public_html/audit/";$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);$uploadOk = 1;$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);// Check if image file is a actual image or fake imageif(isset($_POST["submit"])) {    // Allow certain file formats     if ($_FILES['file']['type'] == 'text/plain') {        echo "<br>Sorry, only txt files are allowed.";        $uploadOk = 0;    }    // Check if $uploadOk is set to 0 by an error    if ($uploadOk == 0) {        echo "<br>2) Sorry, your file was not uploaded.";        // if everything is ok, try to upload file    } else {        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {            echo "The new file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";	    echo "<br>If there was already a file uploaded with the same name then it has been overwritten.";        } else {            echo "<br>Sorry, there was an error uploading your file.";        }    }}echo "<br><br>Upload again? <a href='uploader.php'>yes</a> / <a href='default.html'>no</a>";echo "<br><br>Return to <a href='default.html'>audit page</a>.";	?>

This works for getting the file into the same directory on the web host as the page. I can integrate the form into the main page, but I'm not following how I then get the file to display in the textarea.

 

Thanks,

Andrew

Link to comment
Share on other sites

After the file is uploaded you can read the contents of it (e.g. with file_get_contents) and then print that in the textarea tag. You don't need to move the file if you don't need to save it, you can just read the contents of the temp file.

Link to comment
Share on other sites

Thanks. I've just looked at file_get_contents, but I'm not seeing how I use it with the code in the original post that parses the file appropriately into the textarea. I don't want to simply open and display the txt file. I need to parse it. Am I to somehow replace the xmlhttp.open and xmlhttp.send with the file_get_contents? Sorry, I'm lost.

Edited by SerenityNetworks
Link to comment
Share on other sites

For a normal file upload like you show in post 5, the code to process that form and handle the uploaded file would end with printing out a form, including a text area that would contain the contents of the file. So the user sees the upload form, they select the file, press submit, the page refreshes, and they're looking at a form that has the contents of the file. This doesn't require Javascript. If you want to use Javascript then you need to use FileReader to read the file. file_get_contents is one way that PHP would read the file, not Javascript.

  • Like 1
Link to comment
Share on other sites

Jeez! That was easy! I'm not sure why the AJAX/JSON path was suggested to me when this does the same in my situation and seems to be more flexible in that it works whether I host the page on a local server (like XAMMP) or on my web host. I was able to replace all that lengthy code in post 1 with just the following.

 

Is there something I'm missing for why I should continue with the AJAX/JSON strategy? (I'm just a hobbyist and not a developer. So there is lots I don't know.)

 

Thanks again,

Andrew

<input type='file' accept='text/plain' onchange='openFile(event)'><hr><textarea id="id01" style="overflow:auto;" cols="48" rows="23"></textarea><script> var openFile = function(event) {    var input = event.target;    var reader = new FileReader();    reader.onload = function(){      var myArr= reader.result;    document.getElementById("id01").innerHTML = myArr;    };    reader.readAsText(input.files[0]);  };</script>
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...