Validation of file extension before uploading file
It's possible to check only the file extension, but user can easily rename virus.exe to virus.jpg and "pass" the validation.
For what it's worth, here is the code to check file extension and abort if does not meet one of the valid extensions: (choose invalid file and try to submit to see the alert in action)
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"]; function Validate(oForm) { var arrInputs = oForm.getElementsByTagName("input"); for (var i = 0; i < arrInputs.length; i++) { var oInput = arrInputs[i]; if (oInput.type == "file") { var sFileName = oInput.value; if (sFileName.length > 0) { var blnValid = false; for (var j = 0; j < _validFileExtensions.length; j++) { var sCurExtension = _validFileExtensions[j]; if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) { blnValid = true; break; } } if (!blnValid) { alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", ")); return false; } } } } return true;}
<form onsubmit="return Validate(this);"> File: <input type="file" name="my file" /><br /> <input type="submit" value="Submit" /></form>
Validate file's extension & size before uploading
The validation rules and and request data validation against it happens on the server once the Request data is received.
So naturally even if you try to upload 2GB file or a zip file, it will have to reach the server before it gets validated against the validation rules.
You must also implement some validation in the frontend to prevent such issues.
Say for example you can check the mime type and size of the file being uploaded on the frontend (via javascript) and only if it passes the validation here on frontend allow request to be made to the server with the uploaded file.
However never rely only on validation on the frontend. Validation at server level is must.
For example to validate file being uploaded does not exceed 20MB in size
function isValidSize(file) {
const errors = [];
const maxUploadSizeInBytes = 20 * 1024 * 1024;
let valid = true;
if (file.size > maxUploadSizeInBytes) {
valid = false;
let sizeInKb = maxUploadSizeInBytes / 1024;
let sizeForHumans = sizeInKb < 1024
? `${sizeInKb} KB`
: `${sizeInKb / 1024} MB`;
this.errors.push(
`The file exceeds the maximum allowed size of ${sizeForHumans}`
);
}
return valid;
}
Function to validate mime type of the file being uploaded against allowed mime types
isValidType(file) {
const errors = [];
let acceptedMimes = "jpg,jpeg,png,webp"
.trim()
.split(",")
.map(type => `image/${type}`);
let valid = true;
if (!acceptedMimes.includes(file.type)) {
valid = false;
let phrase = acceptedMimes.replace(/,/g, " or ");
this.errors.push(
`The file type is not allowed. Please upload ${phrase} file.`
);
}
return valid;
}
Validation on Server (backend) is a MUST
Frontend validation is for better user experience and to save some unnecessary network requestsIs possible to validate file size and extension before upload at the same time?
When you select a File from the File Selector Dialog u get a Files Array Object. This object is having information about the File. You can access single File like.
this.files[0]
To Access Size. You can use
this.files[0].size.
Validating file extension in AngularJs before uploading
You can use this simple javascript to validate. This code should be put inside a directive and on change of file upload control.
var extn = filename.split(".").pop();
Alternatively you can use javascript substring method also:
fileName.substr(fileName.lastIndexOf('.')+1)
Validate file extension before uploading whole file formidable (node.js)
I've found the solution in a other SO post, it's the same answer but the answer was hard to find because I was looking specifically for something called before the file is uploaded. The code I am using now (you can remove filetype check in the form.on('file'
form.onPart = function (part) {
if(!part.filename || part.filename.match(/\.(jpg|jpeg|png)$/i)) {
this.handlePart(part);
}
else {
console.log(part.filename + ' is not allowed');
}
}
Source uploading files using express.js and node, limiting extensions
EDIT: I would also like to point out that this doesn't disallow an user to rename an .exe to a .jpg and then he can get it through.
how to validate files before uploading in angular 6
Your question is a bit (lot) vague. I assume you mean, how do you get the File
object from an input in Angular. Dead simple. The same way you would with vanilla(ish) JS.
In your component, create a function to read your file:
readFile(fileEvent: any) {
const file = fileEvent.target.files[0];
console.log('size', file.size);
console.log('type', file.type);
}
And apply it to the (change)
event on your input in your template:
<input type="file" (change)="readFile($event)">
You can do whatever you like with the file after that. The sample function just gets the size and type, as per your question.
Stackblitz Example: https://stackblitz.com/edit/angular-vpvotz
As a (slight) aside, rather than using any
as the fileEvent
type, you can define an interface to give you type hinting.
interface HTMLInputEvent extends Event {
target: HTMLInputElement & EventTarget;
}
While you're at it, also add the File
type too. So your function becomes:
readFile(fileEvent: HTMLInputEvent) {
const file: File = fileEvent.target.files[0];
console.log('size', file.size);
console.log('type', file.type);
}
But, you don't have to. Although any
types are not recommended.
jquery - Check for file extension before uploading
I would like to thank the person who posted the answer, but he has deleted the post. We can do it like this.
$("#yourElem").uploadify({
'uploader': ...,
'script': ...
'fileExt' : '*.jpg;*.gif;', //add allowed extensions
.....,
'onSelect': function(e, q, f) {
var validExtensions = ['jpg','gif']; //array of valid extensions
var fileName = f.name;
var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
if ($.inArray(fileNameExt, validExtensions) == -1){
alert("Invalid file type");
$("#yourElem").uploadifyCancel(q);
return false;
}
}
});
Thanks for the answer, it really worked...
Related Topics
Fixing JavaScript Array Functions in Internet Explorer (Indexof, Foreach, etc.)
How to Replace All Dots in a String Using JavaScript
How to Raw Url Encode/Decode in JavaScript and Ruby to Get the Same Values in Both
How to Get the Name of the Currently Running Function in JavaScript
How to Ignore JavaScript Exceptions When Working with Webdriver (Htmlunit, Ruby Bindings)
Rendering Raw HTML with Reactjs
D3.Js Drawing Geojson Incorrectly
How to Round Up a Number in JavaScript
Installing a Local Module Using Npm
Is There an Equivalent of the _Nosuchmethod_ Feature for Properties, or a Way to Implement It in Js
How to Remove "Disabled" Attribute Using Jquery
Async Function Not Returning Value, But Console.Log() Does: How to Do
Jquery Ajax Success Callback Function Definition
How to Convert a Float Number to a Whole Number in JavaScript
Vue 2 - Mutating Props Vue-Warn
JavaScript Change Background Color on Click
Jquery Jump or Scroll to Certain Position, Div or Target on the Page from Button Onclick