javascript HTML 4 相当于 HTML 5 的 FileReader?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5397991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:03:40  来源:igfitidea点击:

HTML 4 equivalent of HTML 5's FileReader?

javascriptcross-browser

提问by Jon Artus

I've got a web page which needs to be able to load files into the DOM from the local machine on which the browser is running. I've found that this is very easy to do using the HTML 5 File API.

我有一个网页,它需要能够从运行浏览器的本地机器将文件加载到 DOM 中。我发现使用 HTML 5 File API 很容易做到这一点。

I can just do:

我只能这样做:

var reader = new FileReader();  
reader.onload = function (fileContents) { ... load contents to a div ... }
reader.readAsText(f) //where f is an HTML5 File object

Annoyingly, I need this to work in IE7, and also some earlier versions of Firefox which don't support the API. Is there any easy way to load a local file into the DOM in older browsers?

烦人的是,我需要它在 IE7 以及一些不支持 API 的早期版本的 Firefox 中工作。有没有什么简单的方法可以在旧浏览器中将本地文件加载到 DOM 中?

Many thanks!

非常感谢!

采纳答案by Jon Artus

Further to the other answers here, it does appear that there's no consistent way of doing this client-side (other than Flash) for older browsers.

除了此处的其他答案之外,似乎确实没有针对旧浏览器执行此客户端(Flash 除外)的一致方法。

For IE7/8 however, I've managed to hack something together using ActiveX.

然而,对于 IE7/8,我已经设法使用 ActiveX 一起破解了一些东西。

var filePath = f:\oo.txt;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var textStream = fso.OpenTextFile(filePath);
var fileData = file.ReadAll();

I can then pass this to the same function as reader.onload in the question above. Obviously this is a bad, hacky solution, and liable to be blocked by some security policies - it does at least work for IE7 though!

然后我可以将它传递给与上述问题中的 reader.onload 相同的函数。显然,这是一个糟糕的、hacky 的解决方案,并且容易被某些安全策略阻止 - 不过它至少对 IE7 有效!

回答by driis

No, you cannot do that in older browsers. FileReader (any file system access really) is a new HTML5 feature which is not supported in older browsers.

不,您不能在较旧的浏览器中执行此操作。FileReader(任何文件系统访问)是一个新的 HTML5 功能,旧浏览器不支持。

Your best option in an older browser is either:

您在旧浏览器中的最佳选择是:

  1. A Silverlight, Flash or Java app (or similar) that runs on the client-side and has local file system access.
  2. Having the user upload files using the <input type="file">element, and do your processing server-side.
  1. 在客户端运行并具有本地文件系统访问权限的 Silverlight、Flash 或 Java 应用程序(或类似应用程序)。
  2. 让用户使用该<input type="file">元素上传文件,并在服务器端进行处理。

回答by Haochi

Looks like you can do that through Flash. Flash alternative for FileReader HTML 5 API

看起来你可以通过 Flash 做到这一点。FileReader HTML 5 API 的 Flash 替代品