I'm able to launch a file-browser using an HTML Form + JQuery but am having a hard time getting past this point. New to HTML, JQuery, JS.
Essentially, I have a series of existing, empty fields on our page that, after selecting an XML from the file-browser, need to wind up populated with information, parsed from the XML.
Just looking for more open, general direction and resources, haven't been able to find much on the subject. Thanks!
Here is an example using an input type="file" element to read a selected File using XMLHttpRequest to get an XML DOM document to then populate the form elements with the data found in the XML:
function loadData(fileInput) {
var file = fileInput.files[0];
var fileURL = URL.createObjectURL(file);
var req = new XMLHttpRequest();
req.open('GET', fileURL);
req.onload = function() {
URL.revokeObjectURL(fileURL);
populateData(fileInput.form, this.responseXML);
};
req.onerror = function() {
URL.revokeObjectURL(fileURL);
console.log('Error loading XML file.');
};
req.send();
}
function populateData(form, xmlDoc) {
var root = xmlDoc.documentElement;
for (var i = 0, l = form.elements.length; i < l; i++) {
var input = form.elements[i];
if (input.name) {
var xmlElement = root.querySelector(input.name);
if (xmlElement) {
input.value = xmlElement.textContent;
}
}
}
}
<form>
<label>Select XML file to load data from:<input type="file" onchange="loadData(this);"></label>
<br>
<label>foo data
<input type="text" name="foo"></label>
<br>
<label>bar data
<input type="text" name="bar"></label>
</form>
This assumes the XML document selected is a simple XML document with a root element of any name and child elements where the element name matches the input name in the HTML form, for instance
<data>
<foo>foo data</foo>
<bar>bar data</bar>
</data>
First, You should convert xml file to JSON. There are a lot of ways to do this. You can find open source suggestions, just google it.
For example: https://code.google.com/p/x2js/.
When JSON will be got you can easy paste it into necessary fields.
Related
I want to extract a string from a text file, convert it to a word scrambler (I figured out that part) and output it in another text file.
I found some code to input a text file and extract the text:
<html>
<h4>Select un file con .txt extension</h4>
<input type="file" id="myFile" accept=".txt" />
<br /><br />
<div id="output"></div>
<script>
var input = document.getElementById("myFile");
var output = document.getElementById("output");
input.addEventListener("change", function () {
if (this.files && this.files[0]) {
var myFile = this.files[0];
var reader = new FileReader();
reader.addEventListener("load", function (e) {
output.textContent = e.target.result;
});
reader.readAsText(myFile);
}
});
</script>
</html>
Input text and extract a text file
<html>
<div>
<input type="text" id="txt" placeholder="Write Here" />
</div>
<div>
<input type="button"id="bt"value="Save in a File"onclick="saveFile()"/>
</div>
<script>
let saveFile = () => {
const testo = document.getElementById("txt");
let data = testo.value;
const textToBLOB = new Blob([data], { type: "text/plain" });
const sFileName = "Testo.txt";
let newLink = document.createElement("a");
newLink.download = sFileName;
newLink.href = window.URL.createObjectURL(textToBLOB);
newLink.style.display = "none";
document.body.appendChild(newLink);
newLink.click();
};
</script>
</html>
But I don't know how to output a string in the first code or how to connect it to the second code. Could someone please show me how to do it or explain how these codes work so that I could try to do it myself in JavaScript?
I will comment each line of JavaScript, that should help you understand.
<script>
/*This creates a global variable with the HTML element input in it. */
var input = document.getElementById("myFile");
/*This creates a global variable with the HTML element div with id output in it. */
var output = document.getElementById("output");
/* this 2 lines are used to set the source and the destination.
The first will get where you put your file, in this case it's the input element.
The second will get the div which content will be replaced by the content of your txt file. */
/* Here we tell to our input element to do something special when his value changes.
A change will occur for example when a user will chose a file.*/
input.addEventListener("change", function () {
/* First thing we do is checking if this.files exists and this.files[0] aswell.
they might not exist if the change is going from a file (hello.txt) to no file at all */
if (this.files && this.files[0]) {
/* Since we can chose more than one file by shift clicking multiple files, here we ensure that we only take the first one set. */
var myFile = this.files[0];
/* FileReader is the Object in the JavaScript standard that has the capabilities to read and get informations about files (content, size, creation date, etc) */
var reader = new FileReader();
/* Here we give the instruction for the FileReader we created, we tell it that when it loads, it should do some stuff. The load event is fired when the FileReader reads a file. In our case this hasn't happened yet, but as soon as it will this function will fire. */
reader.addEventListener("load", function (e) {
/* What we do here is take the result of the fileReader and put it inside our output div to display it to the users. This is where you could do your scrambling and maybe save the result in a variable ? */
output.textContent = e.target.result;
});
/* This is where we tell the FileReader to open and get the content of the file. This will fire the load event and get the function above to execute its code. */
reader.readAsText(myFile);
}
});
</script>
With this I hope you'll be able to understand the first part of this code. Try putting the second part of your code instead of output.textContent and replacing data with e.target.result, that should do what you wish, but I'll let you figure it out by yourself first, comment on this answer if you need further help !
Here's a codepen with working and commented code:
https://codepen.io/MattDirty/pen/eYZVWyK
Motivation: I want to make a browser-based hashing utility so users can compute file hashes without installing software.
The approach I'm considering is a static page with "a file upload button" (except no upload takes place): the user picks a file, and the script computes and displays its hash.
So let's say we have this element on the page:
<input id="file-hasher" type="file" />
This creates a button that allows the users of the web page to select a file via an OS "File open..." dialog in the browser.
Let's say the user clicks said button, selects a file in the dialog, then clicks the "Ok" button to close the dialog.
The selected file name is now stored in:
document.getElementById("file-hasher").value
Here, I'm hoping to use a library like https://github.com/bitwiseshiftleft/sjcl/ to compute the hash of the chosen file. Is there a way to do this or does the browser's security model get in the way?
Yes, you can select a file using the file element, and take a hash of the file locally, 'in-browser', using javascript. The browser's security model does not prevent this; and the hash function from the native Web Crypto API can be used, so there is no need for any external crypto libraries.
Here is a working example:
function hashfile() {
readbinaryfile(fileselector.files[0])
.then(function(result) {
result = new Uint8Array(result);
return window.crypto.subtle.digest('SHA-256', result);
}).then(function(result) {
result = new Uint8Array(result);
var resulthex = Uint8ArrayToHexString(result);
divresult.innerText = 'result: ' + resulthex;
});
}
function readbinaryfile(file) {
return new Promise((resolve, reject) => {
var fr = new FileReader();
fr.onload = () => {
resolve(fr.result)
};
fr.readAsArrayBuffer(file);
});
}
function Uint8ArrayToHexString(ui8array) {
var hexstring = '',
h;
for (var i = 0; i < ui8array.length; i++) {
h = ui8array[i].toString(16);
if (h.length == 1) {
h = '0' + h;
}
hexstring += h;
}
var p = Math.pow(2, Math.ceil(Math.log2(hexstring.length)));
hexstring = hexstring.padStart(p, '0');
return hexstring;
}
<h2>File Hash</h2>
<div>
Select file to take hash of:
<br/>
<input type="file" id="fileselector" onchange="javascript:hashfile();">
</div>
<br/>
<div id="divresult"></div>
The standard browser security model allows you to have the user pick a file and do what you will with it. I'm an older guy and thought surely this kinda mingling with a user's parts would require additional hoops/consent. So #ceving 's answer was best: "Do it and you will see."
Here's a link to a good article: https://humanwhocodes.com/blog/2012/05/08/working-with-files-in-javascript-part-1/
Apologies for not trying first before posting.
There is the code https://jsfiddle.net/bfzmm1hc/1 Everything looks fine but I want to delete some of the files from the set.
I have already found these:
How to remove one specific selected file from input file control
input type=file multiple, delete items
I know that FileList object is readonly, so I can just copy the files to a new array. But what should I do with this new array of File objects? I can't assign it to the files property...
I found a workaround. This will not require AJAX for the request at all and the form can be sent to the server. Basically you could create an hidden or text input and set it's value attribute to the base64 string created after processing the file selected.
<input type=hidden value=${base64string} />
You will probably consider the idea to create multiple input file instead of input text or hidden. This will not work as we can't assign a value to it.
This method will include the input file in the data sent to the database and to ignore the input file you could:
in the back-end don't consider the field;
you can set the disabled attribute to the input file before serialising the form;
remove the DOM element before sending data.
When you want to delete a file just get the index of the element and remove the input element (text or hidden) from the DOM.
Requirements:
You need to write the logic to convert files in base64 and store all files inside an array whenever the input file trigger the change event.
Pros:
This will basically give you a lot of control and you can filter, comparing files, check for file size, MIME type, and so on..
Since you cannot edit the Read Only input.files attribute, you must upload a form using XMLHttpRequest and send a FormData object. I will also show you how to use URL.createObjectURL to more easily get a URI from the File object:
var SomeCl = {
count: 0,
init: function() {
$('#images').change(this.onInputChange);
},
onInputChange: function() {
// reset preview
$('.container').empty();
// reset count
SomeCl.count = 0;
// process files
SomeCl.processFiles(this.files, function(files) {
// filtered files
console.log(files);
// uncomment this line to upload the filtered files
SomeCl.upload('url', 'POST', $('#upload').get(0), files, 'images[]');
});
},
processFiles: function(files, callback) {
// your filter logic goes here, this is just example
// filtered files
var upload = [];
// limit to first 4 image files
Array.prototype.forEach.call(files, function(file) {
if (file.type.slice(0, 5) === 'image' && upload.length < 4) {
// add file to filter
upload.push(file);
// increment count
SomeCl.count++;
// show preview
SomeCl.preview(file);
}
});
callback(upload);
},
upload: function(method, url, form, files, filename) {
// create a FormData object from the form
var fd = new FormData(form);
// delete the files in the <form> from the FormData
fd.delete(filename);
// add the filtered files instead
fd.append(filename, files);
// demonstrate that the entire form has been attached
for (var key of fd.keys()) {
console.log(key, fd.getAll(key));
}
// use xhr request
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
xhr.addEventListener('progress', function(e) {
console.log('lengthComputable', e.lengthComputable);
console.log(e.loaded + '/' + e.total);
});
xhr.addEventListener('load', function(e) {
console.log('uploaded');
});
xhr.addEventListener('error', function(e) {
console.log('this is just a demo');
});
xhr.send(fd);
},
preview: function(file) {
// create a temporary URI from the File
var url = URL.createObjectURL(file);
// append a preview
$('.container').append($('<img/>').attr('src', url));
}
};
SomeCl.init();
.container img {
max-width: 250px;
max-height: 250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="upload">
<input name="other" type="hidden" value="something else">
<input name="images[]" id="images" multiple="multiple" type="file">
<div class="container"></div>
</form>
I'm trying to display data from the xml file by first getting the content of the xml file and storing it in XML DOM. Once the DOM object is created it is then parsed. I used a for loop so as to get data from each child node of the parent node but somehow only the second node's data is showing.
This is the code where the error is:
xmlhttp.open("GET","company.xml", false); //sets the request for calling company.xml
xmlhttp.send(); //sends the request
xmlDoc = xmlhttp.responseXML; //sets and returns the content as XML DOM
//parsing the DOM object
var employeeCount = xmlDoc.getElementsByTagName("Employee");
for(i=0; i<employeeCount.length; i++)
{
document.getElementById("firstName").innerHTML = xmlDoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
document.getElementById("lastName").innerHTML = xmlDoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
document.getElementById("contactNum").innerHTML = xmlDoc.getElementsByTagName("ContactNo")[i].childNodes[0].nodeValue;
}
The XML file:
<?xml version="1.0"?>
<Company>
<Employee category="technical">
<FirstName>Tanmay</FirstName>
<Nickname>Tania</Nickname>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
</Employee>
<Employee category="non-technical">
<FirstName>Taniya</FirstName>
<LastName>Mishra</LastName>
<ContactNo>1234667898</ContactNo>
</Employee>
</Company>
This the output:
How can i display the data from node [0] as well? Any suggestions will be appreciated. Thanks.
The problem is that you're overwriting data from previous Employee on every iteration :
for(i=0; i<employeeCount.length; i++)
{
document.getElementById("firstName").innerHTML = xmlDoc.getElementsByTagName("FirstName")[i].childNodes[0].nodeValue;
document.getElementById("lastName").innerHTML = xmlDoc.getElementsByTagName("LastName")[i].childNodes[0].nodeValue;
document.getElementById("contactNum").innerHTML = xmlDoc.getElementsByTagName("ContactNo")[i].childNodes[0].nodeValue;
}
That's why only the last Employee data remains in innerHTMLs in the end.
I'm trying to upload a single file using standard multipart upload. It should work just as if there was a form on the page with a file field and a text field and a submit button at the bottom. They identify the file, type in a few other strings and click the "upload" button. In this case, though the form is just a dummy used to create a FileForm object. And the text field and file field and drop box are just random DOM elements with JS behind them. (HTML and jQuery/JavaScript below.)
So, concerning the non-form code, it works (meaning the file uploads and I can see the bytes on the server) only if the user uses the <input type="file" .../> element to identify the file.
If the user does a drag and drop of a file onto a spot on the page, I save the file info in a data element and use it from there instead of from the file input field. But when a file is dropped, an error (shown below) occurs because the code isn't allowed to get a single file out of the FileList returned by the drop.
So I put all the relevant code here and set up a fiddle. But, when I strip it down to the jsFiddle (linked below), both methods work.
That truly messes up the whole question. But I'm going to submit it anyway because it has code pulled together and simplified from a lot of older SO questions for doing file uploads and drag & drop. Plus someone might know what could cause the error.
Question: What sorts of things should I look for on my full page that would cause the contents of the dropped FileInfo object to become protected? That's the question for now.
Here's the FIDDLE
Here's the error message:
Error: Permission denied to access property 'length'
if (files.length > 1) {
Here's the HTML
<label for="dropbox">
<span>DROP HERE:</span>
<!-- CSS makes this a big purple bordered box -->
<div id="dropbox"> </div>
<div id="dropfile"></div>
</label>
<label for="inputFile">
<span>FILES:</span>
<input type="file" id="inputFile" name="inputFile"/>
</label>
<input type="button" id="upload" value="Upload"/>
<form enctype="multipart/form-data" method="post" id="fileform"></form>
Here's the JS w/ jQuery
$.event.props.push('dataTransfer');
$("#dropbox").on("drop", function(e) {
e.stopPropagation();
e.preventDefault();
var dt = e.originalEvent.dataTransfer;
var files = dt.files;
// errors on these lines *******************************************
if (files.length > 1) { alert(files.length + " files dropped. Only 1 allowed"); }
var file = files[0];
// errors on these lines *******************************************
$("#dropfile").text(file.name);
$("#dropbox").data("file", file);
try {
$("#inputFile").val(""); // works in some browsers
} catch (e) {
// ignore failure in some browsers
}
});
$("#dropbox").on("dragenter", function(e) {
e.stopPropagation();
e.preventDefault();
});
$("#dropbox").on("dragover", function(e) {
e.stopPropagation();
e.preventDefault();
});
$("#inputFile").change(function(e) { // selecting a file, erases dropped one
$("#dropfile").text("");
$("#dropbox").removeData("file");
});
$("#upload").click(function() {
var data = new FormData($("#fileform")[0]);
var obj = readTextBoxes();
for (var prop in obj) {
data.append(prop, obj[prop]);
}
// HTML file input user's choice(s)...
var dropfile = $("#dropbox").data("file");
if (dropfile) {
data.append("inputFile", dropfile);
} else {
$.each($("#inputFile")[0].files, function(i, file) {
data.append("inputFile[" + i + "]", file);
});
}
var parms = {
url : baseUrl + "v2/document/upload",
type : "POST",
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
data : data,
timeout : 40000
};
var promise = $.ajax(parms);
// ... handle response
});