I want to make a form with React and upload pdf files. I've to implement until here but now my app needs to read data from pdf without saving in backend database etc. The whole functionality works as pre-checker.
Any suggestion?
You can use PDF.js to read the content of PDF file using javascript/jQuery. Here is my working example.
$("#file").on("change", function(evt){
var file = evt.target.files[0];
//Read the file using file reader
var fileReader = new FileReader();
fileReader.onload = function () {
//Turn array buffer into typed array
var typedarray = new Uint8Array(this.result);
//calling function to read from pdf file
getText(typedarray).then(function (text) {
/*Selected pdf file content is in the variable text. */
$("#content").html(text);
}, function (reason) //Execute only when there is some error while reading pdf file
{
alert('Seems this file is broken, please upload another file');
console.error(reason);
});
//getText() function definition. This is the pdf reader function.
function getText(typedarray) {
//PDFJS should be able to read this typedarray content
var pdf = PDFJS.getDocument(typedarray);
return pdf.then(function (pdf) {
// get all pages text
var maxPages = pdf.pdfInfo.numPages;
var countPromises = [];
// collecting all page promises
for (var j = 1; j <= maxPages; j++) {
var page = pdf.getPage(j);
var txt = "";
countPromises.push(page.then(function (page) {
// add page promise
var textContent = page.getTextContent();
return textContent.then(function (text) {
// return content promise
return text.items.map(function (s) {
return s.str;
}).join(''); // value page text
});
}));
}
// Wait for all pages and join text
return Promise.all(countPromises).then(function (texts) {
return texts.join('');
});
});
}
};
//Read the file as ArrayBuffer
fileReader.readAsArrayBuffer(file);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.87/pdf.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input type="file" id="file" name="file" accept="application/pdf">
<br>
<p id="content"></p>
</body>
Related
I have an HTML form that is used to upload a file to the server. This works correctly but now I am trying to expand the capability such that I select a tar file that consists of two binary files. Then untar the files and based on certain conditions either upload the first or the second file.
This is what I have done so far
use FileReader to read the tar file as ByteArray
use untar from js-untar to untar both file
I need help to figure out how to take the ByteArray for either files and add then to the FormData so that I can upload them.
Any help would be appreciated.
Here are snippets from my code
HTML Form
<form id="upform" enctype="multipart/form-data"
action="cgi-bin/upload2.cgi">
Firmware file: <input id='userfile' name="userfile" type="file" width=50 >
<input type
="submit" name="submitBtn" value="send file">
</form>
Untar code
function sendData() {
var formData = new FormData(form);
var action = form.getAttribute('action');
filesize = file.files[0].size;
var reader = new FileReader();
reader.onload = function() {
untar(reader.result).then(
function (extractedFiles) { // onSuccess
console.log('success');
formData.delete('userfile');
var reader2 = new FileReader();
reader2.onload = function() {
formData.append('userfile', reader2.result);
upload(formData);
}
var blob = new Blob([extractedFiles[0]], {type : 'multipart/form-data'});
reader2.readAsDataURL(blob);
// var f = URL.createObjectURL(blob);
},
function (err) {
console.log('Untar Error');
}
)
};
reader.readAsArrayBuffer(file.files[0]);
return;
}
function upload(formData) {
var action = form.getAttribute('action');
reqUpload.open('POST', action, true);
reqUpload.onreadystatechange = uploadState;
document.body.style.cursor = "wait";
var ld = document.getElementById("load");
ld.classList.add("loader");
reqUpload.send(formData);
document.getElementById('progress').style.display = "block";
progTimer = setInterval(ping, 10000);
uploadStarted = true;
return;
}
i want to give the file location url for the code to get my file instead of using input file in html part , to pass the file to the code
the code pasted below works if i use " input type= "file" " to get the file, but if i use url (like below) it gives a error
fileInput1.addEventListener is not a function
at window.onload
here is the code
window.onload = function() {
var z ="C:/Users/akash/Desktop/riidl/UTham.txt"
var fileInput1 = z;
if (fileInput1){
fileInput1.addEventListener('change', function(e) {
var file = fileInput1.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
spamdata=reader.result;
document.getElementById('here').onclick = console.log(spamdata);
}
reader.readAsText(file);
}
});
}
}
Accessing local files is not allowed in JavaScript for security purposes.
Pl refer to this answer for more details.
https://stackoverflow.com/a/372333/3626796
I have a .txt file on my hard drive containing lots of URLs structured like this:
http://url1.com/
http://url2.com/
.
.
.
I want to load them to a var in Firefox's/Chrome's/IE's dev console so that it would be a vector of strings. I plan to visit these pages with a for loop. How can this be done?
<script>
var urls = [
'http://url1.com/',
'http://url2.com/'
];
</script>
You can generate this snippet with code or just have your file export a global variable and then load it via tags.
You can read a file via JavaScript from the page. You cannot upload a file to the developer's console.
I then modified the code bellow a bit to help you further. I added a scrape function that will help you request each URL one at a time.
<div id="page-wrapper">
<h1>Text File Reader</h1>
<div>
Select a text file:
<input type="file" id="fileInput">
</div>
<pre id="fileDisplayArea"><pre>
</div>
<script>
function scrape(urls) {
url = urls.shift()
$.get(function (url) {
// get the url data here
scrape(urls);
});
}
window.onload = function() {
var fileInput = document.getElementById('fileInput');
var fileDisplayArea = document.getElementById('fileDisplayArea');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
scrape(reader.result.split("\n"));
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
});
}
</script>
Modified version of:
Read a local text file using Javascript
The only way di make your JavaScript aware of local files is to HTTP GET them.
So probably you have to put your file somewhere handy in the project folder and procees with an AJAX request.
var httpRequest;
function makeRequest() {
httpRequest = new XMLHttpRequest();
request.open("GET", "files/url.txt", false);
request.send(null);
saveArray(request.responseText);
}
var array = [];
saveArray(string){
array = string.split("\n")
}
You can get the contents of the file to show up in the Console with the below snippet.
var file="file://C:/FileName.txt";
function read(file)
{
var File = new XMLHttpRequest();
File.open("GET", file, false);
File.onreadystatechange = function ()
{
if(File.readyState === 4)
{
if(File.status === 200 || File.status == 0)
{
var Text = File.responseText;
console.log(Text);
}
}
}
File.send(null);
}
I found a simple but not very elegant workaround for the issue. I just copy and paste the list into a var definition. I don't have to do this often, so it is kind of okay.
I have a text file that is being updated regularly and I want to know if it is possible to read the file, line by line, with javascript and save the values in variables and then update the html page with the new values every time the page is loaded. The html page is a simple page to display information at work, not a live web page, and does not require any user input other than just navigating between the two pages. The text file is on a network drive that everyone has access to. Here is an example of what I'm trying to accomplish:
var value1;
var value2;
Read the file with javascript if possible and extract data and assign to value1 and value2.
document.getElementsByClassName("class for <p>")[0].innerHTML = value;
document.getElementsByClassName("class for another <p>")[0].innerHTML = value;
I have googled this but was not able to find anything that worked. If this is not possible with JS, any suggestions on how this can be done differently. Thanks in advance.
At first, you need to use a input[type=file] to get a File.
<input type=file id=file/>
<div id=result></div>
And then use FileReader to read file to target format, just like base64, text, buffer.
const file = document.getElementById('file').files[0]
const result = document.getElementById('result')
const reader = new FileReader
reader.addEventListener('load', () => {
result.innerHTML = reader.result
})
reader.readAsText(file, 'UTF-8')
See: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
You could use the javascript FileReader and input type="file" to read the local files in your machine. Please see the below attached code for example.
<!DOCTYPE html>
<html>
<head>
<script>
function OnFileLoad() {
var file = document.getElementById("FileReader").files[0];
var textType = /text.*/;
var fileDisplayArea = document.getElementById("FileContent");
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function (e) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
} else {
fileDisplayArea.innerText = "File not supported!"
}
}
</script>
</head>
<body>
<input type="file" id="FileReader" onchange="OnFileLoad()" />
<div id="FileContent">Your content will appear here</div>
</body>
</html>
In order to specify the file path you might need to have a server as well. I have attached a sample code here with. You can find the details regarding Specifying the file path here and issues that will happen to read file without a server here
<!DOCTYPE html>
<html>
<head>
<script>
function readTextFile(file) {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
var fileDisplayArea = document.getElementById("FileContent");
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
fileDisplayArea.innerText = allText;
}
} else {
fileDisplayArea.innerText = "File not supported!"
}
}
rawFile.send(null);
}
readTextFile("file:///C:/Users/t0423/Desktop/test.js")
</script>
</head>
<body>
<div id="FileContent">Your content will appear here</div>
</body>
</html>
What techniques are used to load a file (ASCII or Binary) into a variable (var file = "text";) in JavaScript?
You want to use the new HTML5 File API and XMLHttpRequest 2.
You can listen to files being either selected via a file input or drag & dropped to the browser. Let's talk about the input[type="file"] way.
<input type="file">
Let's listen for files being selected.
var input; // let input be our file input
input.onchange = function (e) {
var files = input.files || [];
var file = files[0];
if (file) {
uploadFile(file);
}
};
What you need to create a real multipart file upload request is a FormData object. This object is a representation of the body of your HTTP POST request.
var uploadFile = function (file) {
var data = new FormData();
data.append('filename', file);
// create a HTTP POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', './script.php', true);
xhr.send(data);
xhr.onloadend = function () {
// code to be executed when the upload finishes
};
};
You can also monitor the upload progress.
xhr.upload.onprogress = function (e) {
var percentage = 100 * e.loaded / e.total;
};
Ask if you need any clarification.
If you want to use the new HTML5 way this is how I did it... keep in mind that I made a method called File() and this is not a true HTML5 method its a wrapper to it... this might be changed in the future so beware (maybe rename it).
HTML:
<html>
<body>
<input type="file" id="files" name="file"/>
<button onclick="load()">Load File</button><br /><br />
<div id="content"></div>
<script>
function load() {
var fileObj = document.getElementById("files");
var fp = new File(fileObj);
fp.read(callback);
}
function callback(text) {
var content = document.getElementById("content");
content.innerHTML = text;
}
</script>
</body>
</html>
JavaScript:
function File(name) {
this.name = document.getElementById(name) ? document.getElementById(name).files : name.files ? name.files : name;
}
// Reads the file from the browser
File.prototype.read = function(callback) {
var files = this.name;
if (!files.length) {
alert('Please select a file!?');
return;
}
var file = files[0];
var reader = new FileReader();
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
callback(evt.target.result);
}
};
var data = file.slice(0, file.size);
reader.readAsBinaryString(data);
}
Have the JavaScript being generated inside a PHP or Rails (or whatever you use server-side) and include the file.
<?php
$my_string = file_get_contents('/path/to/file.txt');
?>
<script>
var my_js_file_string = "<?php echo $my_string; ?>";
...
document.write(my_js_file_string);
</script>