简体   繁体   中英

Error with user click on cancel on file upload dialog

i have a input type file like this:

<div class="custom-file btn-file">
    <input height="35px" type="file" class="custom-file-input" id="i_file_1" name="i_file[]" accept="application/pdf, image/jpeg, image/jpg, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet">
</div>

i handle onchange event to render the file in a modal; but i have an issues when user have selected a file that is in the input, and try to change it but being once in the dialog click on cancel it send error.

$(document).on('change', '.btn-file :file', function(evt) {
var size = this.files[0].size;
console.log(size);
});

This error:

Uncaught TypeError: Cannot read property 'size' of undefined
    at HTMLInputElement.<anonymous> (func.js?20180702235402:11)
    at HTMLDocument.dispatch (jquery.min.js?20180702235402:3)
    at HTMLDocument.q.handle (jquery.min.js?20180702235402:3)
(anonymous) @ func.js?20180702235402:11
dispatch @ jquery.min.js?20180702235402:3
q.handle @ jquery.min.js?20180702235402:3

 $(document).on('change', '.btn-file :file', function(evt) { var size = this.files[0].size; console.log(size); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="custom-file btn-file"> <input height="35px" type="file" class="custom-file-input" id="i_file_1" name="i_file[]" accept="application/pdf, image/jpeg, image/jpg, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"> </div> 

You check if you have files object or not. if so then get the size. otherwise fallback to 0 or something like that

 $(document).on('change', '.btn-file :file', function(evt) { var size = this.files[0] ? this.files[0].size : 0; console.log(`size ${size}`); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="custom-file btn-file"> <input height="35px" type="file" class="custom-file-input" id="i_file_1" name="i_file[]" accept="application/pdf, image/jpeg, image/jpg, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM