我需要在我的 Chrome 扩展程序中添加一个浏览按钮。用户单击它并选择一个文件。然后我想检索文件内容(字节)并对其进行一些工作。
我不想将文件提交到远程服务器然后得到响应(如果这甚至可以从 Chrome 扩展程序内部实现),它应该都是客户端的。
这在 Chrome 扩展中可行吗?
最佳答案
您应该查看 FileReader
API .
The
FileReader
object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, usingFile
orBlob
objects to specify the file or data to read.
this question 中有一个很好的使用此接口(interface)的基本示例。 .
一个最小的例子:假设你有一个
<input type="file" id="file">
选择了一个文本文件。var file = document.getElementById("file").files[0];
var reader = new FileReader();
reader.onload = function(e){
console.log(e.target.result);
}
reader.readAsText(file);
如果您需要读取文本以外的其他方法(即二进制数据),请参阅文档。
此外,这是一个很好的概述:Using files from web applications
关于javascript - 在 chrome 扩展中上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24886628/