在使用html5中文件api的时候 ,发现在chrome无法正确获取到选中的文件 而firefox可以
代码如下
html
<input type="file" id="file" multiple>
<input type="button" value="显示文件信息" id="btn">
js
var file = document.getElementById('file');
var oBtn = document.getElementById('btn');
var files = file.files;
oBtn.onclick = function () {
console.log(files,files.length);
};
测试
chrome
firefox
大家有遇到上面的情况吗?是什么原因造成的,html5的文件api在chrome中应该兼容的呀
I tested it and there is a little difference in the implementation of the two browsers. In Firefox, selecting a file will change the contents of the
file.files
array, while in Chrome, a new array will be created and the originalfile.files
object will be replaced entirely. In other words, what you executed before:Only the old objects are saved, new objects will not be obtained after selecting the file.
This phenomenon can be verified by comparing
files === file.files
after selecting the file.The solution is also very simple, don’t save
files
, get it throughfile.files
every time.I tested locally and Chrome can get the file. Did you trigger the button click first?
file['files']
If it still doesn’t work, try jQuery, $(file).prop('files') and see if it works
There are indeed different performances. For this situation, simulation is usually used to solve such problems!