Upload Files from a Simple HTML Page

I’ve been providing example code recipes for uploading files using Filestack’s various SDKs, including JavaScript/TypeScript in Node, PHP, Python, and Ruby so far. But what if you just want to create a simple HTML page and handle file uploads from there? It’s super easy, so here’s a recipe you can start with today:

<html>
  <head>
    <title>My Example Upload Page</title>
    <script src="https://static.filestackapi.com/filestack-js/1.x.x/filestack.min.js"></script>
  </head>
  <body>
    <script>
      var client = filestack.init('APIKEY').picker().open();
    </script>
  </body>
</html>

That’s all it takes to present a File Picker on a page and receive the uploaded files to your Filestack app (the one associated with the APIKEY you swap in to the code example above).

However, you’ll likely want to do at least one more thing beyond uploading the files: capture the resulting File Handles.

When a file is uploaded, a unique File Handle is generated and assigned to that upload. An upload is a two-sided conversation, with the SDK telling the API “here’s a file”, and the API responding “Thanks! Awfully sweet of you to send me this present, and I’m super excited about all the things we can do with it together! For convenience, let’s refer to this file as XYZ123ABC from now on so we’ll know exactly which one we’re talking about in the future!” I mean, it’s a little more technical than that but you get the idea.

The point is, we didn’t catch that return message with our simple example. Here’s one that does:

<html>
  <head>
    <title>My Example Upload Page</title>
    <script src="https://static.filestackapi.com/filestack-js/1.x.x/filestack.min.js"></script>
  </head>
  <body>
    <script>
      var client = filestack.init('APIKEY');
      client.picker({
        onFileUploadFinished: function(response){
          console.log(response.handle);
        }
      }).open();
    </script>
  </body>
</html>

The difference here is that we’re passing an object to the picker as we call it. Inside of that object we can specify various customizations of the behavior of the picker, including defining a function called onFileUploadFinished. As its name implies, the Engineers at Filestack have wired up the Picker to call that function when the file upload has finished, so inside of our definition there we can catch whatever is passed back and call it anything we like. In this example, we’re calling that return value “response” and passing it to our own function definition to be used inside of that scope. Knowing that it is an object containing a property called “handle” for the file handle we’re expecting, we can log that out to the browser’s console to view and use however we like for experimentation.

In a production environment, you’d capture that File Handle and store it somewhere convenient, perhaps associating it with the UserID of the user that uploaded it. Pretty neat, huh? 🙂

Read More →