在chrome扩展名内上传文件 [英] Upload file inside chrome extension
问题描述
我需要在Chrome扩展程序中添加一个浏览按钮.用户单击它并选择一个文件.然后,我想检索文件内容(字节)并对其进行一些工作.
I need to add a browse button inside my Chrome extension. Users click it and choose a file. I then want to retrieve the file contents (bytes) and do some work on it.
我不想先将文件提交到远程服务器,然后获取响应(如果甚至可以从Chrome扩展程序内部实现),则应该全部在客户端.
I don't want to have to submit the file to a remote server and then get the response (if that's even doable from inside a Chrome extension), it should be all client-side.
在Chrome扩展程序中可以这样做吗?
Is this doable inside Chrome extensions?
推荐答案
您应该查看 FileReader
API .
You should be looking at the FileReader
API.
FileReader
对象使Web应用程序可以使用File
或Blob
对象指定要读取的文件或数据,从而异步读取用户计算机上存储的文件(或原始数据缓冲区)的内容.
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.
此问题中是使用此界面的一个非常好的基本示例.
A very good basic example of using this interface is in this question.
一个简单的例子:假设您有一个<input type="file" id="file">
并选择了一个文本文件.
A minimal example: suppose that you have an <input type="file" id="file">
with a text file selected.
var file = document.getElementById("file").files[0];
var reader = new FileReader();
reader.onload = function(e){
console.log(e.target.result);
}
reader.readAsText(file);
如果您需要的不是读取文本(即二进制数据)的方法,请参阅文档.
If you need methods other than reading as text (i.e. binary data), see the docs.
此外,这是一个很好的概述:使用来自Web应用程序的文件
Also, this is a good overview: Using files from web applications
这篇关于在chrome扩展名内上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!