Fill HTML5 Input Fields with Uploaded XML File - javascript

I built an HTML5/JS web application that performs fairly complicated mathematical calculations based on user-provided data. The application works by having several different input fields where users manually type in the information, then submit it for processing. Much of the information that the users input will not change very often (but often enough where hard-coding it would not be economical), and I was interested in seeing if there was a way to allow users to upload XML files with all of the required data custom tailored to each user. The fields would be filled automatically. The user would change their particular XML file as needed to reflect new values prior to getting new computations. Just as an aside, anything server-side is not an option.
Is it possible using HTML5/JS to upload an XML file, read the file contents, and fill input fields automatically?

As I mentioned in my comment, you can accomplish this task without any server-side intervention, provided the browser has proper File API and FileReader support.
Let's say you have a file input element, where your user will select one of these XML files:
<input id="fileChooser" type="file">
Now, you can access whatever file the user selects, grab the associated text/XML, parse it, and assign the values to text input fields on your page. Your code would look something like this:
var fileChooser = document.getElementById('fileChooser');
function parseTextAsXml(text) {
var parser = new DOMParser(),
xmlDom = parser.parseFromString(text, "text/xml");
//now, extract items from xmlDom and assign to appropriate text input fields
}
function waitForTextReadComplete(reader) {
reader.onloadend = function(event) {
var text = event.target.result;
parseTextAsXml(text);
}
}
function handleFileSelection() {
var file = fileChooser.files[0],
reader = new FileReader();
waitForTextReadComplete(reader);
reader.readAsText(file);
}
fileChooser.addEventListener('change', handleFileSelection, false);

Sounds like an ideal candidate for a Saxon-CE application.
However, I don't think you can make it work without any kind of server support. You talk of "uploading" files; that means uploading to the server, and you need to do something on the server to make that possible. It's not possible for a browser application to interact with filestore on the local machine unless you ask your users to turn off security settings which would be unwise (and I don't even know if that's possible any more).

you must use some server-side code anyway, because JS doesn't allow to upload file and even access it on users computer
so you can not get the contents of this file if not uploading it to server (upd: actually you can do it, so this is only a suggestion)
but you can do it in very simple way e.g. submit a form with file input
<form enctype="multipart/form-data" action="/path/to/script" method="post">
<input name="myFile" type="file" />
</form>
to send it using ajax and get the contents of it as a response from the easy script like this:
<?php
if (!$_FILES["myFile"]["error"]) {
header("Content-Type: text/xml");
echo file_get_contents($_FILES["myFile"]["tmp_name"]);
}
?>
I'm using php, but I'm sure it's not a problem to perform it in another language. Of course I know that file uploading is supported only by XHR2 in major browsers, but as far as you are asking about HTML5 this solution will work.
Next step is to add success handler to your ajax request
success: function(data) {
// and parse it
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(data,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(data);
}
}
Great tutorial here. Now you can access xml contents using xmlDoc var like simple DOM document.

Related

How to programmatically select local file in input type="file"

I want read a local txt file with javascript on chrome browser. So, I use <input type="file" .../> and when I select any txt file, I read it. But I dont want select file. I need to load the file with the file path. How is this possible?
Thanks
You can't do this. This is obviously because of security implications: imagine if any website you visit could read your FileZilla preferences file, which contains all your unencrypted FTP passwords? I bet you wouldn't like that.
You have to obtain a File reference (e.g. from an event handler) before being able to manipulate it. More info.
if you want to read file data opened from file dialog:
function readFile(){
var t = document.getElementById("file")
var o = new FileReader();
o.onload = function(t) {
console.log(t.target.result);
}
o.readAsText(t.files[0]);
}
edit: you can't just open files without selecting it first

file Upload Verifier - jQuery/Javascript

Hiee,
I want to design a frontend of an Uploader page so that
only JPG file can be selected
Max file size should be 1mb
I want to do this check in JavaScript [not in PHP or so ...], can anyone help me ?
[I've no code to show]
Javascript solution i found.
If you want jquery only. convert it to jquery :-)
<html>
<head>
<script>
function getSize()
{
var myFSO = new ActiveXObject("Scripting.FileSystemObject");
var filepath = document.upload.file.value;
var thefile = myFSO.getFile(filepath);
var size = thefile.size;
alert(size + " bytes");
}
</script>
</head>
<body>
<form name="upload">
<input type="file" name="file">
<input type="button" value="Size?" onClick="getSize();">
</form>
</body>
</html>
It's unfriendly to users to insist firmly that filenames must indicate file type, but if you disagree with me you can check the filename on your <input> element. Checking actual file content and size is harder, and will require either Flash or new HTML5 features.
(The file name, stripped of any other path information and possibly even disguised with bogus path information, is available as the <input> element's "value" attribute.)
You may check the extensions (which does not check mime type!)
with something like this:
var el = document.getElementById('filename');
var fileName = el.value;
//do some regex magic to validate for /jpg\z/i
Also: You will also HAVE to check on the server. There's nothing stopping anyone with javascript disabled to upload .exe or other creepy large files.
For the rest I don't think there are many currently backwards compatible solutions for javascript. If you really want to do it client side, you might want to look into flash - since it has more permissions to check it. (Still you need to validate on the server side)
Another solution might be the html5 file api:
http://www.w3.org/TR/FileAPI/#dfn-file
examples with firefox >3.6:
https://developer.mozilla.org/en/using_files_from_web_applications
(Still you need to validate on the server)
i think u can use pluploader for your page.that can be handle your requirement very well.this is the link.http://www.plupload.com/example_queuewidget.php

How do I prompt user to save text (xml) to a file?

I've have some javascript code that transforms XML with XSLT. I now want the user to be able to save that new XML (either by prompting them or throwing the new XML up as a file or something so that the user can then save it. Anybody know how to do that?
var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
xmldoc.async = false;
xmldoc.loadXML(responseText); // responseText is xml returned from ajax call
//apply the xslt
var xsldoc = new ActiveXObject("Microsoft.XMLDOM");
xsldoc.async = false;
xsldoc.load("../xslt/ExtraWorkRequest.xslt");
var content = xmldoc.transformNode(xsldoc);
How do I get the user to save the XML (content) as a file?
By default, you can't. Browser isn't supposed to access your local disks for security reasons.
But, if you can ask your user to change it's security settings (and you should not to ask), you can to use FileSystemObject or even your Microsoft.XMLDOM.Save method.
You cannot do it with 100% client-side JavaScript with the default security settings. You'll need to implement some server-side logic. In your case, you'll be able to do the XML transformation server-side, as well.
http://www.bigresource.com/Tracker/Track-javascripts-ijfTJlI9/
http://support.microsoft.com/kb/q260519/
You could construct a data: URI with a media type of application/octet-stream.
function download (data, charset) {
if (!charset) {
charset = document.characterSet;
}
location.href = ["data:application/octet-stream;charset=",
charset, ",", encodeURIComponent(data)
].join("");
}
All browsers except IE support data: URIs. I think IE8 may support them, but only for images. For IE, a workaround could be to send the data to a server (including document.characterSet) and then load a page that has something like the following header:
Content-Type: application/xml; charset={document.characterSet}
Content-Disposition: attachment
If you want to give the file a name too, use Content-Disposition: attachment; filename=....
Also, for any of this to work, you have to convert your XML to a string first.
I do this with code snippets on my blog (user can click on the save button, and the snippet will come up in their default text editor, where they can tweak it and/or copy it into their app).
It works by putting all the textual data inside of a hidden field, and then submits it to a very simple server-side HTTP handler. The handler just grabs the hidden field value and spits it right back out in the response with the right content-disposition header, giving the user the open/save download prompt.
This is the only way I could get it to work.

Is robust javascript-only upload of file possible

I want a robust way to upload a file. That means that I want to be able to handle interruptions, error and pauses.
So my question is: Is something like the following possible using javascript only on the client.
If so I would like pointers to libraries, tutorials, books or implementations.
If not I would like an explanation to why it's not possible.
Scenario:
Open a large file
Split it into parts
For each part I would like to
Create checksum and append to data
Post data to server (the server would check if data uploaded correctly)
Check a web page on server to see if upload is ok
If yes upload next part if no retry
Assume all posts to server is accompanied by relevant meta data (sessionid and whatnot).
No. You can, through a certain amount of hackery, begin a file upload with AJAX, in which case you'll be able to tell when it's finished uploading. That's it.
JavaScript does not have any direct access to files on the visitor's computer for security reasons. The most you'll be able to see from within your script is the filename.
Firefox 3.5 adds support for DOM progress event monitoring of XMLHttpRequest transfers which allow you to keep track of at least upload status as well as completion and cancellation of uploads.
It's also possible to simulate progress tracking with iframes in clients that don't support this newer XMLHTTPRequest additions.
For an example of script that does just this, take a look at NoSWFUpload. I've been using it succesfully for about few months now.
It's possible in Firefox 3 to open a local file as chosen by a file upload field and read it into a JavaScript variable using the field's files array. That would allow you to do your own chunking, hashing and sending by AJAX.
There is some talk of getting something like this standardised by W3, but for the immediate future no other browser supports this.
Yes. Please look at the following file -
function Upload() {
var self = this;
this.btnUpload;
this.frmUpload;
this.inputFile;
this.divUploadArea;
this.upload = function(event, target) {
event.stopPropagation();
if (!$('.upload-button').length) {
return false;
}
if (!$('.form').length) {
return false;
}
self.btnUpload = target;
self.frmUpload = $(self.btnUpload).parents('form:first');
self.inputFile = $(self.btnUpload).prev('.upload-input');
self.divUploadArea = $(self.btnUpload).next('.uploaded-area');
var target = $(self.frmUpload).attr('target');
var action = $(self.frmUpload).attr('action');
$(self.frmUpload).attr('target', 'upload_target'); //change the form's target to the iframe's id
$(self.frmUpload).attr('action', '/trnUpload/upload'); //change the form's action to the upload iframe function page
$(self.frmUpload).parent("div").prepend(self.iframe);
$('#upload_target').load(function(event){
if (!$("#upload_target").contents().find('.upload-success:first').length) {
$('#upload_target').remove();
return false;
} else if($("#upload_target").contents().find('.upload-success:first') == 'false') {
$('#upload_target').remove();
return false;
}
var fid = $("#upload_target").contents().find('.fid:first').html();
var filename = $("#upload_target").contents().find('.filename:first').html();
var filetype = $("#upload_target").contents().find('.filetype:first').html();
var filesize = $("#upload_target").contents().find('.filesize:first').html();
$(self.frmUpload).attr('target', target); //change the form's target to the iframe's id
$(self.frmUpload).attr('action', action); //change the form's
$('#upload_target').remove();
self.insertUploadLink(fid, filename, filetype, filesize);
});
};
this.iframe = '' +
'false' +
'';
this.insertUploadLink = function (fid, filename, filetype, filesize) {
$('#upload-value').attr('value', fid);
}
}
$(document).ready(event) {
var myupload = new Upload();
myupload.upload(event, event.target);
}
With also using PHP's APC to query the status of how much of the file has been uploaded, you can do a progress bar with a periodical updater (I would use jQuery, which the above class requires also). You can use PHP to output both the periodical results, and the results of the upload in the iframe that is temporarily created.
This is hackish. You will need to spend a lot of time to get it to work. You will need admin access to whatever server you want to run it on so you can install APC. You will also need to setup the HTML form to correspond to the js Upload class. A reference on how to do this can be found here http://www.ultramegatech.com/blog/2008/12/creating-upload-progress-bar-php/

Using jQuery, Restricting File Size Before Uploading

On PHP, they have a way to restrict file size AFTER uploading, but not BEFORE uploading. I use the Malsup jQuery Form Plugin for my form posting, and it supports image file posting.
I was wondering if perhaps there's a restriction where I can set how many bytes can pass through that AJAX stream up to the server? That could permit me to check that file size and return an error if the file is too big.
By doing this on the client side, it blocks those newbies who take a 10MB photo shot from their Pentax and try to upload that.
This is a copy from my answers in a very similar question: How to check file input size with jQuery?
You actually don't have access to the filesystem (for example reading and writing local files). However, due to the HTML5 File API specification, there are some file properties that you do have access to, and the file size is one of them.
For this HTML:
<input type="file" id="myFile" />
try the following:
//binds to onchange event of your input field
$('#myFile').bind('change', function() {
//this.files[0].size gets the size of your file.
alert(this.files[0].size);
});
As it is a part of the HTML5 specification, it will only work for modern browsers (v10 required for IE) and I added here more details and links about other file information you should know: http://felipe.sabino.me/javascript/2012/01/30/javascipt-checking-the-file-size/
Old browsers support
Be aware that old browsers will return a null value for the previous this.files call, so accessing this.files[0] will raise an exception and you should check for File API support before using it
I don't think it's possible unless you use a flash, activex or java uploader.
For security reasons ajax / javascript isn't allowed to access the file stream or file properties before or during upload.
I tried it this way and I am getting the results in IE*, and Mozilla 3.6.16, didnt check in older versions.
<img id="myImage" src="" style="display:none;"><br>
<button onclick="findSize();">Image Size</button>
<input type="file" id="loadfile" />
<input type="button" value="find size" onclick="findSize()" />
<script type="text/javascript">
function findSize() {
if ( $.browser.msie ) {
var a = document.getElementById('loadfile').value;
$('#myImage').attr('src',a);
var imgbytes = document.getElementById('myImage').size;
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}else {
var fileInput = $("#loadfile")[0];
var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
var imgkbytes = Math.round(parseInt(imgbytes)/1024);
alert(imgkbytes+' KB');
}
}
</script>
Add Jquery library also.
I encountered the same issue. You have to use ActiveX or Flash (or Java). The good thing is that it doesn't have to be invasive. I have a simple ActiveX method that will return the size of the to-be-uploaded file.
If you go with Flash, you can even do some fancy js/css to cusomize the uploading experience--only using Flash (as a 1x1 "movie") to access it's file uploading features.
I found that Apache2 (you might want to also check Apache 1.5) has a way to restrict this before uploading by dropping this in your .htaccess file:
LimitRequestBody 2097152
This restricts it to 2 megabytes (2 * 1024 * 1024) on file upload (if I did my byte math properly).
Note when you do this, the Apache error log will generate this entry when you exceed this limit on a form post or get request:
Requested content-length of 4000107 is larger than the configured limit of 2097152
And it will also display this message back in the web browser:
<h1>Request Entity Too Large</h1>
So, if you're doing AJAX form posts with something like the Malsup jQuery Form Plugin, you could trap for the H1 response like this and show an error result.
By the way, the error number returned is 413. So, you could use a directive in your .htaccess file like...
Redirect 413 413.html
...and provide a more graceful error result back.
$(".jq_fileUploader").change(function () {
var fileSize = this.files[0];
var sizeInMb = fileSize.size/1024;
var sizeLimit= 1024*10;
if (sizeInMb > sizeLimit) {
}
else {
}
});
Try below code:
var sizeInKB = input.files[0].size/1024; //Normally files are in bytes but for KB divide by 1024 and so on
var sizeLimit= 30;
if (sizeInKB >= sizeLimit) {
alert("Max file size 30KB");
return false;
}
Like others have said, it's not possible with just JavaScript due to the security model of such.
If you are able to, I'd recommend one of the below solutions..both of which use a flash component for the client side validations; however, are wired up using Javascript/jQuery. Both work very well and can be used with any server-side tech.
http://www.uploadify.com/
http://swfupload.org/
It's not possible to verify the image size, width or height on the client side. You need to have this file uploaded on the server and use PHP to verify all this info.
PHP has special functions like: getimagesize()
list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";

Categories

Resources