exporting .txt files in html, and then importing it afterwards - html

So im making a website, and one of its core features I need to get working is getting the web page to export a mundane .txt file containing all the content from the forms I have.
Once that works, I also need to figure out how to import that same file back into the website and have it automatically fill in the text boxes.
How can I go about doing this?

Your question is kind of broad and doesn't show much research effort on your part. It's good form to have a go and then come here when you run into a problem, rather than just ask us to solve your problem for you. Despite that, I'll try to give you some pointers. :)
I recently had a requirement to make a button to download the contents of a div. I made a gist for future reference. You can probably adapt it to your purpose.
Basically what I did was assign a click handler to a HTML button marked 'Download'. When the button is clicked, I create a temporary anchor element on the page and set its href to the contents of the div and then programmatically click on the anchor to fire the download and finally removing the temporary anchor from the page. There's a fallback for Internet Explorer with a different method. I adapted this code from an SO answer some time ago.
var downloadButton = document.getElementById('downloadButton');
downloadButton.addEventListener('click', function () {
//get the contents of the div
var contents = document.getElementById('someDiv').innerHTML;
if (contents.length = 0) {
return;
}
var filename = 'some-filename.txt';
if (navigator.msSaveBlob) { // IE
navigator.msSaveBlob(new Blob([contents], { type: 'text/plain;charset=utf-8;' }), filename);
} else {
var link = document.createElement('a');
link.setAttribute('download', filename);
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(contents));
document.body.append(link);
link.click();
document.body.removeChild(link);
}
});
As for your next requirement, upload the file and importing the data, I'll direct you to the HTML5 Rocks - file handling tutorial.
I just had a crack at a quick file uploader and I have it dumping the file contents to the console. You could, instead, parse the file contents and add the data back to your form elements as required. Here's my test code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Test Page</title>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList
for (var i = 0; i < files.length; i++) {
var reader = new FileReader();
// when the file has been read, print the contents to the console
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) {
console.log(evt.target.result);
}
};
var text = reader.readAsText(files[i]);
}
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('files').addEventListener('change', handleFileSelect, false);
});
</script>
</head>
<body>
<input type="file" id="files" name="files[]" multiple />
</body>
</html>

Related

Fortify Often Misused: File upload Issue

<!DOCTYPE html>
<html>
<head>
<script>
function fileValidation(fileInput) {
var filePath = fileInput.value;
// Allowing file type
// First check file type
const fileTypes = [
".pdf",
"file"
];
if (!fileTypes.includes(fileInput.type)) {
console.log("Invalid file input")
fileInput.value = '';
return false;
}
// Second check file content
var fileContent = fileInput.files[0];
if (fileContent) {
var reader = new FileReader();
reader.readAsText(fileContent);
reader.onload = function (evt) {
console.log(reader.result)
}
reader.onerror = function (evt) {
console.log(reader.error)
}
}
// Third check file size
const fileSize = fileInput.files[0].size / 1024 / 1024; // in MiB
if (fileSize > 2) {
console.log('File size exceeds 2 MiB');
return false;
}
}
</script>
</head>
<body>
<!-- File input field -->
<label for="botFile">File upload</label>
<input type="file" id="botFile" onchange="fileValidation(this)" maxlength="255" name="botFile" accept=".pdf" />
</body>
</html>
Fortify shows this recommendation to fix the issue
Do not allow file uploads if they can be avoided. If a program must accept file uploads, then restrict the ability of an attacker to supply malicious content by only accepting the specific types of content the program expects. Most attacks that rely on uploaded content require that attackers be able to supply content of their choosing. Placing restrictions on the content the program will accept will greatly limit the range of possible attacks. Check file names, extensions, and file content to make sure they are all expected and acceptable for use by the application.
Result:
Tried several other fixes to resolve this Issue. But fortify doesn't eliminate the issue.
Can anyone please suggest the fix/solution ?

NodeJS load a json from a file selector without reloading webpage

Has anyone done this?
I need to be able to grab a JSON file from a input file selector from HTML, after that read it, parse it and show it in the webpage.
The page cannot reload and I don't need to upload/copy it to any of my folders. I just need to read it and show it without reloading the webpage.
Any ideas? I'm on Nodejs. I'm serving static html pages. Apparently it's simple but I'm struggling a lot.
HTML:
<input type="file" onchange='getContent(this)' />
<div id="file-content"></div>
JS:
function getContent(content) {
if (content.files && content.files[0]) {
var contentReader = new FileReader();
contentReader.onload = function(e) {
var output = e.target.result;
document.getElementById('file-content').innerHTML = output;
};
contentReader.readAsText(content.files[0]);
}
}
You can see live preview here

Print Screen to Website [duplicate]

This question already has answers here:
Using HTML5/Canvas/JavaScript to take in-browser screenshots
(7 answers)
Closed 9 years ago.
My user need to screen shot their error message throw my website. They should directly paste from clipboard in my website instead convert the jpeg. Preferable browser is Firefox. I try to use ZeroClipBoard but it works for words not images. Appreciated if anyone could advice and share any links for references.
Simple answer: you can't. There is no web-standards way to read binary data from the clipboard, I also do not believe that Flash or Silverlight does this either (Flash can expose bitmap data from the clipboard, but only under AIR, i.e. not in a browser context).
You could write a small desktop utility program that your users download and run, which will take a screenshot and upload it for them, but without that your users will have to paste the image into Paint, save to disk, and upload with an <input type="file">.
I'm not sure of the compatibility with mozilla but you should look at the onpaste event
https://developer.mozilla.org/en-US/docs/Web/API/element.onpaste
and event.clipboarddata
http://www.w3.org/TR/clipboard-apis/
Cross compatibility is probably is probably going to be an issue.
You can look at the source for wordpress plugin Image Elevator http://wordpress.org/plugins/image-elevator/
Look at admin/assests/js/image-elevator-global.js for ideas.
After looking at the plugin I got the following code to work. It reloads the page image with whatever you paste. Works on chrome but not firefox.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
document.onpaste = function (e) {
var items = e.clipboardData.items;
for (var i = 0; i < items.length; ++i) {
// uploads image on a server
var img = items[i].getAsFile();
var oData = new FormData();
oData.append('file', img);
var req = new XMLHttpRequest();
req.open("POST", "test-pastup.php");
req.onreadystatechange = function() {
setTimeout(function() {
var img = $('img').clone();
$('img').remove();
$('body').prepend(img);
}, 100);
}
req.send(oData);
return;
}
}
</script>
</head>
<body>
<img src="aaa.png" />
<input/>
</body>
</html>
for the server side - test-pastup.php
<?php
$source = $_FILES['file']['tmp_name'];
move_uploaded_file( $source, 'aaa.png' );
?>

HTML input tag file handling

In this code for the PDF reader pdf-js there is an input tag to let the user upload an input file
<input id="fileInput" class="fileInput" type="file" oncontextmenu="return false;" style="visibility: hidden; position: fixed; right: 0; top: 0" />
This input tag is not a part of any form. Once the user uploads the file, where does it go? Where is the code that processes the file? (I'm asking in general, not necessarily specific to this piece of code.)
"Then it's interesting. This code doesn't have server side"
No, It doesn't.
Pdf.js is a client side program that written with javascript. So that works on javascript side.
It actually takes the file that you wanna show, and does whatever must be done like converting the buffer to Uint8Array than renders it.
All processes happen on javascript side. No server side, no file upload.
Here is an article about reading local files in javascript
Here is the related part of code in pdf.viewer.js
window.addEventListener('change', function webViewerChange(evt) {
var files = evt.target.files;
if (!files || files.length === 0)
return;
// Read the local file into a Uint8Array.
var fileReader = new FileReader();
fileReader.onload = function webViewerChangeFileReaderOnload(evt) {
var buffer = evt.target.result;
var uint8Array = new Uint8Array(buffer);
PDFView.open(uint8Array, 0);
};
var file = files[0];
fileReader.readAsArrayBuffer(file);
PDFView.setTitleUsingUrl(file.name);
// URL does not reflect proper document location - hiding some icons.
document.getElementById('viewBookmark').setAttribute('hidden', 'true');
document.getElementById('download').setAttribute('hidden', 'true');
}, true);

reading text files in html5 + javascript, result is browser dependant

I've been going over this for hours now, looking through different options on the web trying to understand -and not just replicate- how to load a text file. I couldn't get to work ANY of the examples I found, that is, until I changed from chromium to firefox. As an example, the code in stackoverflow question: HTML5 File api, reading in an xml/text file and displaying it on the page? which I write here for simplicity:
<!DOCTYPE html>
<html>
<head>
<title>reading xml</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<input type="file" id="files" name="files[]" multiple />
<output id="list"></output>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList
for (var i = 0, f; f = files[i]; i++) {
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Print the contents of the file
var span = document.createElement('span');
span.innerHTML = ['<p>',e.target.result,'</p>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the file
reader.readAsText(f);
// reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
</body>
works great on firefox. I cannot get it to work in chromium. What am I missing?! thanks.
I'm using Chromium 18.0.1025.168 (Developer Build 134367 Linux) Ubuntu 11.10
Could it be this?
for (var i = 0, f; f = files[i]; i++) {
Shouldn't your second part be a conditional. Something like i < files.length?
For security reasons, to load local files I have to call chromium from the command line using:
chromium-browser --allow-file-access-from-files
ATENTION: you have to close all chromium windows for this to take effect.
Just lost about four hours because of this...