می توان قبل از اینکه کاربر فایلی را سمت سرور ارسال کند پسوند فایل را چک کرد و از یک رفت و برگشت بیهوده به سرور جلوگیری کرد .
یک پیاده سازی ساده به کمک jQuery :
var ext = $('#my_file_field').val().split('.').pop().toLowerCase();
if($.inArray(ext, ['gif','png','jpg','jpeg']) == -1) {
alert('invalid extension!');
}
در کد بالا ابتدا پسوند فایل انتخاب شده توسط کاربر پیدا میشود ، سپس به کمک متد inArray با آرایه ای از پسوندهای دلخواه ما مقایسه میشود و در صورت معتبر نبودن پیغامی به کاربر نشان میدهد.
کد بالا را میتوان در رویداد Change کنترل فایل یا در هنگام Post شدن Form اطلاعات قرار داد.
کاملا واضح است که این روش را میتوان به راحتی دور زد و نباید به آن اکتفا کرد.
مثال این روش را
اینجا بررسی کنید.
بررسی سایز فایل :
در اکثر برنامههای تحت وب کاربرها محدود به Upload فایل تا سایز خاصی هستند ، این مورد را هم میتوان قبل از Upload کنترل و اعتبارسنجی کرد :
//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);
});
این روش تا زمانی که کاربر JavaScript را غیر فعال نکرده قابل اطمینان است.