如何使用FileReader读取多个文件的内容

如何使用FileReader读取多个文件的内容

本文介绍了如何使用FileReader读取多个文件的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我正在尝试从JavaScript中读取多个文件的内容。一个文件工作正常,但如果我选择多个文件,onload似乎被称为适当的次数,但只显示最后一个文件的内容。其他文件显示为空白。任何想法都会很棒。



我猜测在我尝试显示之前可能没有读过该文件,但我不确定为什么。任何帮助都会很棒。谢谢,



Brian



Hi,

I'm trying to read the contents of multiple files from JavaScript. One file works fine but if I select multiple files, onload seems to be called the appropriate number of times but only the contents of the last files are displayed. Other files are displayed as blank. Any ideas would be great.

I'm guessing the file may not have been read before I try and display but I'm not sure why. Any help would be great. Thanks,

Brian

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>File API</title>
    <script>
	function processFiles()
	{

    	var filelist = document.getElementById('files').files;


		for(var i=0; i<filelist.length; i++)
		{

			var file = filelist[i];
			var textType = /text.*/;


			if (file.type.match(textType))
			{
				var reader = new FileReader();
				reader.>
</head>
<body>
Select a text file:
<input type="file" multiple id="files" onchange="processFiles()" />
</body>
</html>

推荐答案

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type='file' accept='text/plain' onchange='openFile(event)'><br>
<ul id='filelist'></ul>
<script>
  var openFile = function(event) {
    var input = event.target;

    var reader = new FileReader();
    reader.onload = function(){
      var text = reader.result;
      var ul = document.getElementById("filelist");
      var li = document.createElement("li");
      li.innerHTML = reader.result;
      ul.appendChild(li);
    };
    reader.readAsText(input.files[0]);
  };
</script>

</body>
</html>



了解详情:]


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>File API</title>
    <script>
    function processFiles()
    {
        var filelist = document.getElementById('files').files;
        for(var i=0; i<filelist.length; i++)

        {

            writefiles(filelist[i]);

        }

    }



    function writefiles(file)

    {

        var reader = new FileReader();

        reader.onload = function()

        {

            document.getElementById('output').innerText += reader.result;

        }

        reader.readAsText(file, "UTF-8");

    }

    </script>
</head>
<body>
Select a text file:
<input type="file" accept='text/plain' multiple id="files" onchange="processFiles()" />
<pre id="output"></pre>
</body>
</html>


这篇关于如何使用FileReader读取多个文件的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 18:48