我有一个像这样的输入类型文件:
<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>
我处理onchange事件以模式方式呈现文件;但是当用户选择输入中的文件并尝试更改它,但是在对话框中单击一次取消它发送错误时,我遇到了问题。
$(document).on('change', '.btn-file :file', function(evt) {
var size = this.files[0].size;
console.log(size);
});
此错误:
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>
答案 0 :(得分:0)
您检查是否有files
个对象。如果是这样,则获取大小。否则回退到0或类似的值
$(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>