【发布时间】:2020-09-12 09:36:31
【问题描述】:
我正在编写一个 jQuery 脚本来一次上传多张图片,但在上传之前调整它们的大小。调整上传大小时一切正常。
不过,我在脚本的 2 个相互冲突的部分遇到了麻烦。
首先是html
<form method="post" action="{{url('filemanager/manage')}}" enctype="multipart/form-data">
{{csrf_field()}}
<div class="input-group " >
<label id='fmg-multiple-input-label'>
<input id='fmg-multiple-input' type="file" name="fmg-multiple-input[]" class="myfrm form-control " multiple="multiple">
</div>
<button type="submit" class="btn btn-danger btn-upload" style="margin-top:10px">Submit</button>
</form>
以下是脚本
//FIST BLOCK
$('#fmg-multiple-input').change(function (e) {
//write the selected file names in the label
var files = [];
for (var i = 0; i < $(this)[0].files.length; i++) {
file = $(this)[0].files[i];
files.push(file.name);
//filemanager.resizeAndUpload(file);
}
$('#fmg-multiple-input-label').html(files.join(', '));
});
//SECOND BLOCK
if (window.File && window.FileReader && window.FileList && window.Blob) {
$(document).on('click', '.btn-upload', function (e) {
e.preventDefault();
$("#fmg_upload_progress").show().empty();
$('#fmg_file_form').fadeOut(10);
//var input = $("#fmg-multiple-input").get(0);//a jQuery selector doesn't return a DOM element but a jQuery object
var input = document.getElementById('fmg-multiple-input');//equivalent return the DOM element
console.log(input);
for (var i = 0; i < input.files.length; i++) {
filemanager.resizeAndUpload(input.files[i]);
}
});
} else {
alert('The File APIs are not fully supported in this browser.');
}
请注意,所有这些都在文档准备好的包装内。
第一行是在标签中写下文件的名称。
单独使用效果很好
第二行代码块从输入字段中为每个文件调用一个方法。此方法调整图像大小并执行 ajax 请求上传。
单独来看这个块工作正常
当我尝试同时使用这两种方法时,问题就出现了。在第二行中,
console.log(input)
返回一个错误,说明输入为空。
似乎第一个块使输入无效。有没有办法防止这种行为?
【问题讨论】: