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;
}
Related
I have a page with a file input where the user is supposed to upload an excel file to insert a large amount of records to a specific table. I found this Javascript code to help validate if the inserted file has one of the requested Excel extensions:
var hash = {
'xls': 1,
'xlsx': 1,
};
function checkExtension() {
var filename = $("#uploadFile").val();
var re = /\..+$/;
var ext = filename.slice(filename.lastIndexOf(".") + 1).toLowerCase();
if (hash[ext]) {
return true;
} else {
alert("Invalid file type. Please insert a valid Excel file.");
event.preventDefault();
return false;
}
}
However, as efficient as this code is at validating the file's extension, it won't validate the file's content allowing someone to upload a file with different type of content but it's extension renamed to ".xls" or ".xlsx". How can i get around this scenario?
You can Properly Validate Your Excel File in 3 steps
In Asp.net FileUploader Control has an Attribute Called 'accept' <asp:FileUploader accept='.xls,.xlsx'/>. It will by default let the user to select only xls and xlsx extension file. However still user can choose All file options to upload another file.
Verify if the Extension of the Filename contains .xls from Javascript as well as Code Behind.
Use Aspose.Cells dll and try to fetch the xls file it will return Exception 'InvalidFileFormatException' if the File is not xls or xlsx.
I want to stop file upload event when I upload the file more than 5mb or if my file extension is not .jpg or .png. I found a code but when I try to upload the invalid file type then it only gives me alerts that I have uploaded the wrong file but it does not cancel the event.
Here is the code:
<script>
function checkFile(fieldObj)
{
var FileName = fieldObj.value;
var FileExt = FileName.substr(FileName.lastIndexOf('.')+1);
var FileSize = fieldObj.files[0].size;
var FileSizeMB = (FileSize/5485760).toFixed(2);
if ( (FileExt != "png" && FileExt != "jpg") || FileSize>5485760)
{
var error = "File type : "+ FileExt+"\n\n";
error += "Size: " + FileSizeMB + " MB \n\n";
error += "Please make sure your file is in png or jpg format and less than 5 MB.\n\n";
alert(error);
return false;
}
return true;
}
</script>
and here is html code:
<input type="file"onchange="checkFile(this)"name='sec_2_img'>
You need to clear the value of 'sec_2_img'. You do this by adding fieldObj.value = ""; after alert(error) and before return false;. This will remove the file name from sec_2_img and force user to select a new one while still showing the message so user knows what to do.
1.) Don't use alerts, they are annoying and the browsers will block them pretty fast, so your users won't get any message anymore.
Use a modal window or add a styled element with the error-message somewhere into your form.
2.) If you need to have a valid file to submit this form, you have to add a event-handler to the submit-event of the form and stop the trasmission.
3.) your check for file-extension is case-sensitive, this might give you problems on windows, and your calculation of the fileSize is wrong.
I am creating a web portal where end user will upload a csv file and I will do some manipulation on that file on the server side (python). There is some latency and lag on the server side so I dont want to send the message from server to client regarding the bad format of uploaded file. Is there any way to do heavy lifting on client side may be using js or jquery to check if the uploaded file is "comma" separated or not etc etc?
I know we can do "accept=.csv" in the html so that file extension has csv format but how to do with contents to be sure.
Accessing local files from Javascript is only possible by using the File API (https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications) - by using this you might be able to check the content whether it matches your expectations or not.
Here's some bits of code I used to display a preview image clientside when a file is selected. You should be able to use this as a starting point to do something else with the file data. Determining whether its csv is up to you.
Obvious caveat:
You still have to check server side. Anyone can modify your clientside javascript to pretend a bad file is good.
Another caveat:
I'm pretty sure that you can have escaped comma characters in a valid csv file. I think the escape character might be different across some implementations too...
// Fired when the user chooses a file in the OS dialog box
// They will have clicked <input id="fileId" type="file">
document.getElementById('fileId').onchange = function (evt) {
if(!evt.target.files || evt.target.files.length === 0){
console.log('No files selected');
return;
}
var uploadTitle = evt2.target.files[0].name;
var uploadSize = evt2.target.files[0].size;
var uploadType = evt2.target.files[0].type;
// To manipulate the file you set a callback for the whole contents:
var FR = new FileReader();
// I've only used this readAsDataURL which will encode the file like data:image/gif;base64,R0lGODl...
// I'm sure there's a similar call for plaintext
FR.readAsDataURL($('#file')[0].files[0]);
FR.onload = function(evt2){
var evtData = {
filesEvent: evt,
}
var uploadData = evt2.result
console.log(uploadTitle, uploadSize, uploadType, uploadData);
}
}
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.