我正在嘗試從本地磁盤上傳 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>
)
}
我讀過我可以使用 File API 或 Blob API。我都試過了,但沒有一個能夠真正訪問所包含的資料。他們只能訪問路徑“C:\fakepath\data.json”。
我一直在網上尋找答案,我能找到的只是看起來我需要先將它發送到服務器。但是,我的應用是 chrome 擴展,沒有網路服務器。
誰能幫我解決這個問題?將不勝感激。
uj5u.com熱心網友回復:
像這樣嘗試(使用files[0]代替value)
const upload = async () => {
let bb = new Blob([uploadValue.current.files[0]], {type: "application/json"})
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/512298.html
