Below I have a jquery code which includes a textbox where the user can choose a file:
var $imagefile = $('<input />')
.attr({
type: 'file',
name: 'imageFile',
id: 'imageFile'
});
What my question is that how can I get it so that it restricts the user from picking jpeg, gif or png files? I want user to browse for a file, then click on the submit button. If the file type is correct then show confirmation message else display an alert stating “Wrong file format has been chosen for the Image”.
Below is the validation() where it displays the alerts:
function validation() {
var marks = parseInt($("#total-weight").text());
var _qid = "";
var _msg = "";
var maxQuestions = <?php echo (int)@$_POST['textQuestion']; ?>;
var questionsAdded = $('tr.optionAndAnswer').length;
var alertValidation = "";
// Note, this is just so it's declared...
$("tr.optionAndAnswer").each(function() {
_qid = $("td.qid",this).text();
_msg = "You have errors on Question Number: " + _qid + "\n";
$(".textAreaQuestion",this).each(function() {
if (!this.value || this.value.length < 5) {
alertValidation += "\n\u2022 You have not entered a valid Question\n";
}
if (alertValidation != "") {
return false; //Stop the each loop
}
});
$(".txtWeightRow",this).each(function() {
if (!this.value) {
alertValidation += "\n\u2022 Please enter in a figure for Number of Marks for this Question\n";
}
if (alertValidation != "") {
return false; //Stop the each loop
}
});
if(alertValidation != ""){
return false;
}
});
The
<input type="file">has long (since it was introduced in 1995) had anacceptattribute, where you can list MIME-types that you want to accept, e.g.accept="image/*". It’s only very recently that browsers have started to support it, though. Right now, Opera 11, Chrome 16, Firefox 9. IE doesn’t.Can’t recall whether the use of
acceptactually filters the files listed in the file selection dialog box, or just restricts the files accepted after the user has selected them. May vary from browser to browser and OS to OS.But yes, you can check the file extension after the file has been selected. Something like (untested):
In any event, you’ll want to validate the file types on the server, and not depend on the client to ensure they’re the right type.