Could you tell me (for example, Google could not), if I can set the default file format for file upload.
Currently it allows to upload all files (please refer to the file image *.*), however I would like to limit to a specific file format.
All help is appreciated.
Environment:
NO HTML5
Backend: Struts
FrontEnd: jQuery-1.6.1
File upload plugin uses iframe to upload files.
you can use this
<input type="file" id="myfile" accept="image/gif, image/jpeg, image/png, image/jpeg" />
but using this. user can anytime change the filter.
additionally you should use
javascript or jquery to validate.
<script type ="text/javascript">
var validFiles=["bmp","gif","png","jpg","jpeg"];//array of allowed extensions
function OnUpload()
{
var obj = document.getElementById("myfile");
var source=obj.value;
var ext=source.substring(source.lastIndexOf(".")+1,source.length).toLowerCase();
for (var i=0; i<validFiles.length; i++)
{
if (validFiles[i]==ext)
break;
}
if (i>=validFiles.length)
{
alert("This not a valid file upload file with an extention of one of the following:\n\n"+validFiles.join(", "));
return false;
}
return true;
}
</script>
Related
I want to build the system that allows the client to upload the geojson files from html form and this data will show on the leaflet map. While I try to do so, It shows the error code 405. I want to submit the form containing geojson file and load this file using leaflet-omnivore plugin.
My html file as,
<section class="addVectorLayer">
<form action="" method="POST" class="vector">
Click to add your vector layer. It support Json, Geojson, csv, gpx and kml formats.
<input type="file" name="files" id="input_files">
</form>
</section>
my js file is here,
geojson.onlode = function() {
geojson.readAsDataURL(document.getElementById('input_files').files[0]);
};
omnivore.geojson(geojson.result).addTo(map);
Please note that I don't want async call.
I added some code based on this plugin. That works for me little. The better way is highly appriciated.
var fileInput = document.getElementById('input_files');
fileInput.addEventListener('change', function (event) {
var file = fileInput.files[0],
fr = new FileReader();
fileInput.value = ''; // Clear the input.
extention = file.name.split('.')[1]
if (extention === 'geojson') {
fr.onload = function () {
var layer = omnivore.geojson(fr.result).addTo(map);
map.fitBounds(layer.getBounds());
};
fr.readAsDataURL(file);
}
});
Using fr.readAsText()and JSON.parsing the result allows you to feed the result to L.geoJson(), no need for the omnivore plugin you are using.
An extension of a file to be upload within a HTML form may be validated using JQuery's Valdation plugin:
<form enctype="multipart/form-data" id="form-id">
<input type="file" name="file-id" id="file-id" />
</form>
This may be validated by JQuery's Validation Plugin using the a rule
$("#form-id").validate({
rules: {
file-id: {
extension: ["jpg","png","gif"]
}
});
For our usage, simple extension validation is not sufficient as users tend to rename graphics their files before uploading without converting them. E.g. we retrieve a PDF graphics wich cannot be convert to e.g. png's by libgd.
Is there a way to examine the real content of a graphics file and prevent uploading not processable formats?
Yes, it is possible (or may be possible depending on the specific browser). The HTML File API allows you to get a file's MIME type. See the article Reading files in JavaScript using the File APIs for details, but the basic idea is as follows:
For a file input element:
<input type="file" id="file-input">
You can get the FileList object, the File object(s) from that, each of which has a type property that resolves to a MIME type:
$("#file-input").on("change", function (evt) {
var files = evt.target.files;
$.each(files, function (i, file) {
if (file.type === "image/jpeg") {
alert("It's a JPEG");
}
else if (file.type === "image/png") {
alert("It's a PNG");
}
else {
alert('The file MIME type is "' + file.type + '"');
}
});
});
If you need go beyond the MIME type, you can open and read the file's contents via the FileReader API. Method readAsArrayBuffer will give you the file contents as an array of typed bytes.
What you are looking for is the MIME type of the file.
If you are using the HTML file chooser you can get the type using:
document.getElementById('fileChooserID').files[0].type
Note that this will check the MIME type in the client side so it will not be enough. You can never trust the client side alone for validation.
In server side you should inspect the request content-type located on the request's HEAD.
I give user the option of uploading a file like this
<form action="#" onsubmit="return Checkfiles(this);">
<center><input type="file" id="filename">
<input type="submit" value="Go!"></center>
</form>
When user uploads the file, I validate the file using the following javascript function
<script type="text/javascript">
function Checkfiles()
{
var fup = document.getElementById('filename');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "pdf" )
{
return true;
}
else
{
alert("Upload pdf files only");
fup.focus();
return false;
}
}
</script>
Evertything is working fine with it.
But I want to validate file by some other means and not just by its extension
I will give reason for doing this. I renamed an image file to image.pdf and now its in pdf format but couldnt be opened.
So I want to validate a pdf file in exact way. Is there any other way to check other than by its extension?
Edit
I want to do validation at server end using jsp page. So what should I do for that?
Thanks in ADVANCE :)
To validate a filetype on javascript, here are some ways:
// Your way: getting the extension and checking it.
// I suggest this way instead of using indexOf:
var ext = fileName.split('.').reverse()[0]
// Splits by '.', reverse the array, and returns the first element
// Another way: checking the type of the file
if ( fup.files[0].type === 'application/pdf' ) {
console.log( 'It is validated!' )
}
Live example: http://jsbin.com/akati3/2 thanks to https://stackoverflow.com/a/4581316/851498
But then, you should really validate this on the server side as others said.
Any kind of javascript validation is only for users comfort. Everything should be validated on serverside too. User can easily disable or modify any javascript code.
Anyway. you can't check file contents in javascript.
In PHP, you can use http://www.php.net/manual/en/function.finfo-file.php to detect file type by it's contents. Most of other languages should have similar functionality.
As far as I know, checking if a pdf actually is a pdf can only be done on server side. You could try and open it with IText or something similar; I bet it throws some sort of exception when you try opening or modifying something else then a PDF.
On my page I have a bunch of file upload fields (all with name="files[]" so it can be processed as a PHP array).
They are all located in one of two divs, lets call them 'div1' and 'div2'.
How can I use javascript so that onSubmit, it checks the file types and all the files in div1 can only be 'pdf', and all the files in div2' can only be 'pdf' or 'doc'?
A simple alert popup box will do (ie. "Files can only be pdf")
Any suggestions?
****************UPDATE*******************
Made a more relevant question: Add a filetype validation to phpmailer?
You can make this:
HTML:
<form method="post" enctype="multipart/form-data" name="form">
<input type="file" name="file" /><br />
<input type="file" name="file" />
<input type="submit" />
</form>
JavaScript:
var fileInput = document.getElementsByName("file");
for(var i = 0, len = fileInput.length; i < len; i++) {
fileInput[i].addEventListener('change',
function(e) {
if(this.files[0].name.match(/\.pdf$/) == null) {
alert('Files can only be PDF.');
return;
}
},
false
);
}
File upload elements are heavily protected in browsers, and JS has minimal access to its contents. Anything dealing with the file itself is pretty much locked off, as any hole in the system could allow a malicious site to steal files from the user's computer.
The easiest workaround is to just put up a small note next to the fields say "PDF Only!" and then use a server-side script to confirm that it is a pdf.
You can address the form element and read the name attribute, then you get the file name and can work with the file extension.
But this may only be used to make it easier to the user - so you can detect wrong file types before the uploading process.
It is NOT a protection in any way.
You can also pass the filestypes expected to the dialog itself. Most file managers and browsers respect it and display only the files of the type you want to choose, but the user can click a dropdown and select "view all files" and pic whatever files he/she want.
This is done with the accept attribute.
If you want to help the user choosing the right file both methods above are appropriate and I would even use them together.
If you want to protect your service from wrong filetypes, you have to evaluate the files server side. A file extension checking is not appropriate, there are php functions available to determine the real mimetype of a file.
You can check on submit for each file upload using this code:
var parts = document.getElementById('myFileField').value.split('.');
if (parts[parts.length-1] != 'pdf') {
alert('Invalid extension. Needs to be PDF.');
}
Incorporating work by The Mask,
var fileInputs = document.getElementsByName("files[]");
for (var ele in fileInputs) {
if (ele.parentNode.id = 'div1') {
var parts = ele.value.split('.');
if (parts[parts.length-1] != 'pdf') {
alert('Invalid extension: "' + ele.value + '". Needs to be PDF.');
}
}
else if (ele.parentNode.id = 'div2') {
var parts = ele.value.split('.');
if (parts[parts.length-1] != 'pdf' && parts[parts.length-1] != 'doc') {
alert('Invalid extension: "' + ele.value + '". Needs to be PDF or DOC.');
}
}
}
I want to restrict a file upload control to allow PDF files only. I want to use JavaScript for that.
I want to apply that JavaScript in file upload event.
You can check the file name on submit.
"hook to the <form>'s onsubmit with whatever method" {
filename = theFileElement.value;
if (!/\.pdf$/i.test(filename)) {
alert("error");
return false;
}
return true;
}
Note that this only checks if the file has an extension of .pdf. It does not (and cannot) check whether the file is really a just PDF or actually a nasty virus. Moreover, client side Javascript can easily be bypassed, so you should perform the check again on the server side.
var ext = fname.split(".");
var x=ext.length;
if(ext[x-1] == 'pdf'){
alert("Please upload doc file");
document.form.fname.focus();
return false;
}