file Upload Verifier - jQuery/Javascript - 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

Related

Fill HTML5 Input Fields with Uploaded XML File

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.

Reading manifest file contents of a JAR from Javascript

Is it possible to read manifest file contents from Javascript. Requirement is to upload a jar file, read the manifest file content and then display different fields based on manifest file in browser (client side) and then send data to server.
Here is a basic example, tested in chrome.
I've never seen a JAR manifest, but the simplistic code below worked on the demo JAR files i found floating around.
That part is not tricky anyway, ripping open the zip and grabbing the file is, and here's one way:
<html>
<form><input type=file></form>
<script src="http://stuk.github.io/jszip/jszip.js"></script>
<script src="http://stuk.github.io/jszip/jszip-load.js"></script>
<script src="http://stuk.github.io/jszip/jszip-inflate.js"></script>
<script>
function getManifest(e){
var file=e.target.files[0];
var reader = new FileReader();
reader.onload = function(e) {
var zip = new JSZip(e.target.result);
var manifest = zip.files['META-INF/MANIFEST.MF']
.data
.trim()
.split(/\s*\n+\s*/)
.map(function(a,r){
r=a.split(/\s*:\s*/);
this[r[0]] = r[1];
return this;
},{})[0];
alert(JSON.stringify(manifest, null, "\t"));
};
reader.readAsArrayBuffer(file);
}
document.forms[0].elements[0].onchange=getManifest;
</script>
</html>
of course, you'll want to swap out the file input for a binary ajax call, but it's about impossible to demo such interaction in a paragraph of code like a file input allows...
it's pretty easy, thanks to jszip. about that: see http://stuk.github.io/jszip/ for general info and http://stuk.github.io/jszip/examples/get-binary-files-xhr2.html for a binary ajax demo.
Supposing you talk about Java server app:
No it's not possible.
You need to expose the info from manifest somehow, e.g. through a REST API. See [RestEasy|http://www.jboss.org/resteasy].
And then read it through XmlHttpRequest.
PS: It's not a good idea to expose whatever in META-INF or WEB-INF - it's a security risk.

creating a file by javascript

i am trying to make a file in javascript, but it doesn't be saved in the root.
when the file is made, the sentence i write has to be stored in the file.
or loading a sentence from a textbox is also fine for me.
can anyone give me help??
function createFile() {
var fso = new ActiveXObject('Scripting.FileSystemObject');
var fileObj = fso.CreateTextFile("G:\\soonrok.txt", true);
fileObj.WriteLine("Hello, I am Soonrok!!!");
}
<td>
<input type="button" value="save" onClick="createFile()">
The best you're going to be able to do with JavaScript is create a cookie.
http://www.w3schools.com/js/js_cookies.asp
Or you could do something that only works for IE with ActiveX.
Or see the link from #AurA for Chrome Only tricks and/or ways to download files from a server.

What is the equivalent of wget in javascript to download a file from a given url?

"wget http://www.example.com/file.doc" downloads that file to the local disk.
What is the equivalent of the above in javascript? for example, consider the following html snippet.
<html>
<head>
<script language="JavaScript">
function download_file() {
var url = "http://www.example.com/file.doc"
//
// Question:
//
// what should be done here to download
// the file in the url?
//
}
</script>
</head>
<body>
<input type="button" value="Download" onclick="download_file()">
</body>
</html>
Please suggest a solution that is compliant with all the browsers.
Sangeeth.
After a exploring more than a month, with a help of my friend, we were able to find out the following.
The website where the file is hosted is not allowing us to download the file using window.location = url; or window.open(url);
Finally we had to use the data-downloadurl support from HTML5 as follows
Click here to download the file
We embed this html into the host html and when clicked on the link, it triggers the download.
Why not use:
function download_file() {
var url = "http://www.example.com/file.doc"
window.location = url;
}
See https://developer.mozilla.org/en/DOM/window.location
If you need to open this in a new window/tab first then use:
function download_file() {
var url = "http://www.example.com/file.doc"
window.open(url);
}
See https://developer.mozilla.org/en/DOM/window.open
First thing that always comes in mind of every answerer to this question is executing wget shell command from java script.I'm almost certain that that's not possible because of
major security risk.
You pretty much need to have ajax which sends command to command line
either through php, or another scripting language via ajax...
You could probably make that happen with something like http://www.phantomjs.org/
I am saying probably because I read it from somewhere.

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