Search code examples
javascriptform-data

How can we know the content of a file from a Javascript File object?


One common way to make asynchronous file upload that I could find on the web works as follow :

myUpload(ev) {
  ev.preventDefault();

  const data = new FormData();
  data.append('file', this.uploadInput.files[0]);

  /* Do the upload with something like axios */ 
  axios.post('http://localhost:8000/upload', data)
    . ...
}

I cannot explain the following :

  • the object this.uploadInput.files[0] is a File javascript object.
  • From the documentation I could find (see for instance this), and from the log I tried on the console, javascript File objects store neither the file content, nor the file path.

Therefore, how can the FormData object retrieve the file data we want to send ?


Solution

  • FormData probably doesn't, but the browser does because when axios provides the FormData object to the browser's ajax features (XHR or fetch), the browser can use the data in¹ the File object to read and send the file.

    Your own JavaScript code could also use the data in the File object to read the file, using FileReader (another browser-supplied feature).

    File doesn't directly contain the file's data, but it does contain information the browser can use to read the file (without exposing its actual location to your code).


    ¹ Probably not literally in the File object. More likely an indirect relationship between the two using data privately-held by the browser.