Chrome扩展中如何读取<input type="file">上传文件内容(无需服务器)
解决Chrome扩展中本地JSON文件导入chrome.storage的问题
你遇到的核心问题是:出于浏览器安全限制,input[type="file"]的value属性只会返回带C:\fakepath\的伪路径,无法直接通过这个路径读取本地文件内容。不需要后端服务器,直接用浏览器的File API就能完成文件内容读取与存储,以下是具体修正方案:
错误根源
你的upload函数中,用伪路径字符串创建Blob,自然只能得到路径文本,而非文件实际内容:
let bb = new Blob([uploadValue.current.value], {type: "application/json"})
修正后的完整代码
直接从<input>的files属性获取File对象,读取内容后解析并存入chrome.storage:
const ImportExport = () => { const uploadValue = useRef() const download = () => { chrome.storage.sync.get(null, res => { let blob = new Blob([JSON.stringify(res)], {type: "application/json"}) let url = window.URL.createObjectURL(blob) chrome.runtime.sendMessage({method: 'download', data: url}, () => { window.URL.revokeObjectURL(url) }) }) } const upload = async (e) => { e.preventDefault(); // 获取选中的第一个文件 const file = uploadValue.current.files[0]; if (!file) return; try { // 读取文件文本内容 const contents = await file.text(); // 解析JSON数据 const importedData = JSON.parse(contents); // 保存到chrome.storage.sync await chrome.storage.sync.set(importedData); console.log("数据导入成功"); } catch (err) { console.error("导入失败:", err); alert("请选择有效的JSON文件"); } } return ( <div className="flex flex-col items-center justify-start rounded-sm mx-auto w-1/2 shadow-md h-5/6"> <h2 className="text-3xl m-5">Import/Export</h2> <form onSubmit={upload}> <label htmlFor="import" className={styles.button}>Select JSON File</label> <input ref={uploadValue} type="file" accept="application/json" id="import" /> <button type="submit" className={styles.button}>Import</button> <button onClick={download} className={styles.button}>Export</button> </form> <h3 className="text-2xl m-3">Note:</h3> <p className="text-center w-1/2">This exports the data to .JSON file which can then be used to import back to chrome storage</p> </div> ) }
关键修改点
- 从
uploadValue.current.files[0]获取实际的File对象,替代无效的伪路径 - 使用
file.text()异步读取文件内容(现代浏览器原生支持,替代传统FileReader写法) - 添加错误捕获逻辑,处理JSON解析失败或文件读取异常的情况
- 调整表单提交逻辑,用
onSubmit触发导入操作,避免误触发
补充说明
- 所有操作均在Chrome扩展本地完成,无需后端服务器
accept="application/json"已限制文件类型,降低无效文件导入概率- 导入时会覆盖chrome.storage.sync中同名键值对,若需合并数据,可先调用
chrome.storage.sync.get(null)获取现有数据,合并后再保存
内容的提问来源于stack exchange,提问作者Cedric M.
相关产品推荐
相关产品推荐

