我已经使用 html5+ 文件阅读器上传了带有文件预览的文件,它工作正常,除了用户选择的旧文件从输入文件字段中被破坏,如果用户在新的单一浏览点击中选择。
这是 js fiddle https://jsfiddle.net/sco3pq3b/
html
<p> UPLOAD </p>
<input type="file" multiple="yes" name="photo[]" id="photos">
<div id="preview"></div>
js
$("#photos").change(function(){
var fileList = this.files;
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
for(var i = 0; i < fileList.length; i++){
if (regex.test(fileList[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').append('<div class="imgLinkWrap"><a class="fancybox" href="' + e.target.result +'">'+fileList[0].name.toLowerCase()+'</a></div>');
}
console.log(fileList[i]);
reader.readAsDataURL(fileList[i]);
} else {
alert(file[0].name + " is not a valid image file.");
$('#preview').html("");
return false;
}
}
});
在不使用任何插件或 ajax 的情况下,是否可以在单击新浏览文件后保留旧文件?
最佳答案
您可以将上传的文件存储在将被保留的本地文件数组中。这就是我修改你的 js 的方式,这似乎工作正常。
var fileList=[];
$("#photos").change(function(){
fileList.push.apply(fileList,this.files); // appends files objects to local array
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
for(var i = 0; i < fileList.length; i++){
if (regex.test(fileList[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
$('#preview').append('<div class="imgLinkWrap"><a class="fancybox" href="' + e.target.result +'">'+fileList[0].name.toLowerCase()+'</a></div>');
}
console.log(fileList[i]);
reader.readAsDataURL(fileList[i]);
} else {
alert(file[0].name + " is not a valid image file.");
$('#preview').html("");
return false;
}
}
});
关于javascript - 在多个文件 uploader 中单击新文件浏览后如何保留旧文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34545290/