Using fetch() to Upload a File

File uploads are trickier than it seems. There are a few ways to do it on the client side. It really is just sending a POST/PUT request to the server you’re uploading to, but set the content type to multipart/form-data and the body is no longer strictly strings or JSON, but binary files, or any format you desire. One way to do it to use a form submission, which looks like this:

  <form action="/" enctype="multipart/form-data" method="post">
    <input type="file" name="file-to-upload">
    <input type="submit" value="Upload">

This is fine and really simple. But if you run into a situation like mine, where I’m uploading a JavaScript generated file, you’ll need to use a JavaScript function. The jQuery/AJAX and XMLHttpRequest ways for sending a request is well documented everywhere, but here’s a native JavaScript function if you don’t want to include the entire library in you page for the functionality.

That’s the window.fetch() method.

In my case, I was generating .obj files from a THREE.js scene, which can get quite large. In the snippet I will replace just with a string that represents a triangle with.

let uploadObj = () => {
  let obj =
    'o' +
    '\nv -0.500000 -0.500000 0.500000' +
    '\nv 0.500000 -0.500000 0.500000' +
    '\nv -0.500000 0.500000 0.500000' +
    '\nvt 0.000000 0.000000' +
    '\nvt 1.000000 0.000000' +
    '\nvt 0.000000 1.000000' +
    '\nvn 0.000000 0.000000 1.000000' +
    '\nf 1/1/1 2/2/1 3/3/1';

  let form = new FormData();
  form.append('triangle.obj', new Blob([obj]));

  fetch('/', {
    method: 'POST',
    body: form
  }).then(response => {
    return response.blob();

One thought on “Using fetch() to Upload a File”

Leave a Reply

Your email address will not be published.