Home > Software design >  How to access contents of file uploaded from <input type="file" /> without sending t
How to access contents of file uploaded from <input type="file" /> without sending t

Time:10-17

I'm trying to upload JSON file from local disk to upload chrome storage but when I use the tag and useRef on the current value, it only returns the filename prefixed with 'C:\fakepath...'

ImportExport Component:

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>
  )
}

I've read that I can use File API or Blob API. I've tried both but none of them where able to actually access the data contained. They could only access the path 'C:\fakepath\data.json'.

I've been looking scraping the web for answers and all I could find is it looks like I need to send this to a server first. However, my app is a chrome extension and has no web server.

Can anyone help me figure this out? It would be much appreciated.

CodePudding user response:

Try it like this (use files[0] instead of value)

  const upload = async () => {
    let bb = new Blob([uploadValue.current.files[0]], {type: "application/json"})
   ...
  }
  • Related