Filereader – 再次上传相同的文件不起作用

我有点像绘图应用程序。 用户可以保存项目然后加载它们。 当我第一次加载一个文件(例如project1.leds)在应用程序中进行一些更改但没有保存它然后再次加载相同的文件(project1.leds)没有任何反应。 我不能多次加载同一个文件。 如果我加载其他文件,它的工作。

码:

$("#menu-open-file").change(function(e){ var data=[]; var file = null; file = e.target.files[0]; console.log(file) var reader = new FileReader(); reader.onload = function(e){ data=JSON.parse(reader.result); x=data[0].SIZE[0]; y=data[0].SIZE[1]; if(x==15) x=16; if(x==30) x=32; if(x==60) x=64; if(y==15) y=16; if(y==30) y=32; if(y==60) y=64; createLeds(x,y,data,false,false); clearActiveTools(); var svg = $('#contener').find('svg')[0]; svg.setAttribute('viewBox','0 0 ' + x*20 + ' ' + y*20); $("#contener").css("width",x*20).css("height",y*20); $("#contener").resizable({ aspectRatio: x/y, minHeight: 200, minWidth: 200, }); wiFirst = $("#contener").width(); hiFirst = $("#contener").height(); } reader.readAsText(file); }); 

我可以删除/删除缓存文件吗? 它甚至在浏览器中缓存了吗?

这是因为你正在调用函数onchange。 如果上载相同的文件,则文件输入的值与上一次上载相比没有变化,因此不会触发。 这也解释了为什么它可以上传不同的文件。 无需清除缓存,您可以通过在读取文件后重置输入字段的值来解决此问题。

 $("#menu-open-file").change(function(e){ var data=[]; var file = null; file = e.target.files[0]; if(file !== ''){ console.log(file) var reader = new FileReader(); reader.onload = function(e){ data=JSON.parse(reader.result); x=data[0].SIZE[0]; y=data[0].SIZE[1]; if(x==15) x=16; if(x==30) x=32; if(x==60) x=64; if(y==15) y=16; if(y==30) y=32; if(y==60) y=64; createLeds(x,y,data,false,false); clearActiveTools(); var svg = $('#contener').find('svg')[0]; svg.setAttribute('viewBox','0 0 ' + x*20 + ' ' + y*20); $("#contener").css("width",x*20).css("height",y*20); $("#contener").resizable({ aspectRatio: x/y, minHeight: 200, minWidth: 200, }); wiFirst = $("#contener").width(); hiFirst = $("#contener").height(); } reader.readAsText(file); $("#menu-open-file")[0].value = ''; } }); 

上述答案的唯一问题是您的HTML将在上传后不再显示文件名。 相反,它将继续说“没有选择文件”,这可能会让用户感到困惑。

要解决此问题,您可以隐藏输入并将其替换为复制输入显示的标签,如下所示:

HTML:

  No file chosen 

CSS:

 #myFileInput { display: none; } #myFileLabel { border: 1px solid #ccc; border-radius: 4px; cursor: pointer; font-size: 12px; margin-top: 5px; padding-left: 6px; padding-right: 6px; } #myFileName { margin-left: 5px; } 

JavaScript的:

 var file = null file = e.target.files[0]; //variable to get the name of the uploaded file var fileName = file.name; //replace "No file chosen" with the new file name $('#myFileName').html(fileName); 

很好地解释了如何在这里做到这一点: https : //tympanus.net/codrops/2015/09/15/styling-customizing-file-inputs-smart-way/