我正在尝试从本地磁盘上传 JSON 文件以上传 chrome 存储,但是当我在当前值上使用标签和 useRef 时,它只返回前缀为“C:\fakepath...”的文件名
导入导出组件:
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 () => {
let bb = new Blob([uploadValue.current.value], {type: "application/json"})
let contents = await bb.text()
console.log(contents) // logs 'C:\fakepath\notes.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>
<label htmlFor="import" className={styles.button}>Import</label>
<input onChange={upload} ref={uploadValue} type="file" accept="application/json" id="import" />
<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>
)
}
我读到过我可以使用文件 API 或 Blob API。我都试过了,但没有一个能够实际访问所包含的数据。他们只能访问路径“C:\fakepath\data.json”。
我一直在网上寻找答案,但我能找到的只是看起来我需要先将其发送到服务器。但是,我的应用程序是一个 chrome 扩展,没有网络服务器。
谁能帮我解决这个问题?将不胜感激。
最佳答案
像这样尝试(使用 files[0]
而不是 value
)
const upload = async () => {
let bb = new Blob([uploadValue.current.files[0]], {type: "application/json"})
...
}
关于javascript - 如何在不发送到服务器的情况下访问从 <input type ="file"/> 上传的文件内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73996378/