0

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 ?

Archimondain
  • 374
  • 2
  • 17
  • 1
    JavaScript is not a stand-alone programming language in this context: it is there to [*script a host environment*](https://stackoverflow.com/a/39946046/3757232), in this case the browser. It can manipulate the host using hooks that host provides. While the *browser* has full access, *JavaScript's* access is heavily mediated. In other words, it's browser voodoo and you just ask it to do it's thing. – Jared Smith Nov 02 '18 at 17:14

1 Answers1

2

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.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • I see. So it means for instance that if I use axios to post an object that contains my FormData as an attribute, then it would probably won't load the file data, because the browser will not detect it and 'work its magic' ? – Archimondain Nov 02 '18 at 17:36
  • @Archimondain - I'd have to defer to the axios documentation on that, it depends on exactly what you're doing and whether axios supports it and ensures it provides the `FormData` object to the browser. – T.J. Crowder Nov 02 '18 at 17:40
  • Well, I will test that. Thanks anyway. – Archimondain Nov 02 '18 at 17:43