Handling File Uploads Painlessly with Filepicker

Building a complete web form is some of the best practice for new web developers. You get a taste of a whole bunch of technologies when doing so. You have to use HTML in a more advanced way, you get to work with CSS for styling, you probably have to use JavaScript for client-side validation or AJAX type things, and, finally, you have to use some sort of server-side language like PHP to do something with the submitted form values. It also even introduces you to more advanced things like HTTP Request Methods – GET and POST.

Anyways, the point is working with forms can be quite the lift for some people. On top of this, the second you start introducing files, it only gets more complex. Doing things like styling <input type="file"> elements, working on the front-end with real-time uploads, and storing the file securely on the server can be incredibly difficuly and/or time-consuming. This is where Filepicker for web developers will come in handy.

Filepicker is a web service for taking the headache out of file uploads. It allows you to easily allow your users to “pick” files on your website or app with ease. On top of this, it also allows you to easily tap into third-party APIs so users can even select files from cloud providers like Dropbox, Google Drive, or even Facebook.

This tutorial will get you started with integrating Filepicker onto your website or application. To demo this, we’ll walk you through building an app where users can upload files, store them on the cloud, and see them appear in near real-time on the current page. Here’s a picture of what we’ll be building or click the demo link to check it out:

filepicker-facemash-demo

Why Filepicker?

Filepicker is an easy to use cloud service for making file uploads easy. It’s not just for doing uploads on the web though, they also provide libraries for tons of other technologies:

  • iOS
  • Android
  • Python
  • Ruby on Rails
  • django
  • CakePHP
  • Meteor
  • PhoneGap
  • Node.js
  • WordPress

Basically anyone can tap-into their API and use them for “picking files” regardless of the language or platform you’re using. Here’s what it looks like on the web:

Filepicker popup modal

By taking over the file upload process of your site or application, they can also middle-man some extra cool things. They make it very easy to optionally do things like hosting, cropping the photo, pulling from third-parties like Facecbook or cloud storage, facial recognition, cross-browser and responsive, and much more.

Getting Started

Signup

Filepicker is a cloud-service. So the first step to get started is to create an account with them. Don’t worry though, they provide a free service with plenty of room until the first paid tier. With this, you get:

  • 3 GB of Bandwidth
  • 20MB maximum file size
  • 500 files per month

You can signup on their registration page.

Create a new app

Just like when creating a Facebook or Twitter app, you need to first create an application to get a unique App ID.

Filepicker - Step 1

Filepicker - Step 2

Filepicker - Step 3

After this, we’re all set to begin coding.

Setting Up Your Page

We’re building a simple single page demo with Filepicker that let’s anyone upload a photo to a wall of photos. The first thing we need to do is setup our basic HTML. Here’s what I’ll be using to start as a super basic layout:


<!doctype html>
<head>

    <!-- Meta -->
    <meta charset="utf-8">
    <title>Scotch Face Mash</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

    <!-- Favicon -->
    <link rel="shortcut icon" sizes="16x16 24x24 32x32 48x48 64x64" href="https://scotch.io/favicon.ico">

    <!-- Styles -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="style.css">

</head>
<body>



    <!-- Wall Markup will go here -->


    
    <!-- Scripts -->
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="power.js"></script>

</body>
</html>

Note: This application only uses HTML, CSS, and jQuery. style.css will be used for custom styles and power.js for JS scripts.

Integrating filepicker.js

There are two methods you can use for integrating with filepicker.js with your website. One method is a pure JavaScript approach (we’ll be doing that one) while the other method is to use their ultra simple widget.

JavaScript Method

The first thing you need to do is embed filepicker.js on your website. Simply add a reference to the filepicker.js file like so to our existing code base where the scripts are:


<script src="https//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://api.filepicker.io/v2/filepicker.js"></script>
<script src="power.js"></script>

Now that we added filepicker.js to our markup, it introduces a new global JavaScript object: filepicker.

We can take a quick peek with this in power.js by doing:


console.log(filepicker)

This doens’t do or show much, but it’s a start. We need to start doing stuff with it now. The first step is to set an API key.

You can do this with one line:


filepicker.setKey("A1jBeZwwiQvqb7X20ka21z");

After the API key is set, we can now start using the filepicker object with events such as a click.

Here’s an example with jQuery that limits uploads to images:


// On "click" event with jQuery
$('#big-freaking-button').click(function() {

    // Settings
    filepicker.pick({
        mimetype: 'image/*', /* Images only */
        maxSize: 1024 * 1024 * 5, /* 5mb */
        imageMax: [1500, 1500], /* 1500x1500px */
        cropRatio: 1/1, /* Perfect squares */
        services: ['*'] /* All available third-parties */
    }, function(blob){
        // Returned Stuff
        var filename = blob.filename;
        var url = blob.url;
        var id = blob.id;
        var isWriteable = blob.isWriteable;
        var mimetype = blob.mimetype;
        var size = blob.size;

        console.log(blob)
    });

});

You can do a bunch of cool things with this. You can limit to specific image types, adjust quality, specify which third-party integrations you want to use, if you want it to popup in a new window or appear in a specific container, and more.

It’s all just a bunch of config options. You can read a full list of things to do here.

Widget method

If you’re still working on your JS skills, you can use an out-of-the-box solution with a widget that they provide. This is super easy to use. All you need to do is visit their Quick Start page to be walked through the process of generating your widget.

Here’s what it will roughly look like for you to copy and paste into your form:


<input type="filepicker" data-fp-apikey="A1jBeZwwiQvqb7X20ka21z" name="myName"/>

If you use the pure JavaScript method you can essentially trigger Filepicker whenever you want. On a click, on hover, after a signup, etc. With the Widget, you have to treat it like a replacement for the upload form input.

Handling Uploads

After a user uploads a file to filepicker, we have to decide what to do with it. Filepicker will return the URL of the uploaded file to you, it’s up to you what to do with it.

For this example, we’re just going to dump the URL and store it in a Mongoose database with node. This article won’t cover how we set the node part up, but you can look through our node articles if you’d like to learn more. All we did was create an endpoint to save and retrieve uploads:



GET /api/links /* Retrieves all images */
POST /api/links /* Saves a URL */

Now, here’s our updated code for uploading the picked image:


$('#big-freaking-button').click(function() {

    // Settings
    filepicker.pick({
        mimetype: 'image/*', /* Images only */
        maxSize: 1024 * 1024 * 5, /* 5mb */
        imageMax: [1500, 1500], /* 1500x1500px */
        cropRatio: 1/1, /* Perfect squares */
        services: ['*'] /* From anywhere */
    }, function(blob) {

        // Returned stuff for example
        var filename = blob.filename;
        var url = blob.url;
        var id = blob.id;
        var isWriteable = blob.isWriteable;
        var mimetype = blob.mimetype;
        var size = blob.size;

        // Save to a database somewhere
        // Alternatively you can have filepicker do it for you: https://www.filepicker.com/documentation/storage/
        $.ajax({
            url: '/api/links',
            type: 'POST',
            data: {
                url: blob.url
            },
            success: function(data) {

                // Response from storing the URL successfully
                console.log(data);

            }
        });

    });

});

Filepicker Storage

Here’s the thing though, Filepicker can actually manage your uploads for you with multiple third-party providers so you don’t have to even worry about it. This is great because it eliminates another third-party API to maintain.

They support the following providers:

  • S3
  • Rackspace
  • Azure
  • Dropbox
  • Google Cloud

You can read about Filepicker storage in their docs here.

Populating the Wall

Now that we have Filepicker setup, it’s time to build our wall of images. We’ll need to do two things:

  • Real-time update the wall with the users current image
  • Populate the wall with all uploaded photos on page load

For the current upload

At this point, we’re able to successfully select an image with filepicker, get a URL from it, and then store that URL in a database somewhere. It’s now time to take that URL and update our page.

In order to do this, I use a quick and dirty jQuery templating system I made. We’ll cover this in the tutorial, but you can technically do this however you’d like. Our purpose is just getting this working as a proof of concept for the tutorial.

First thing we’re going to do is create our HTML5 template for images. Here’s what that looks like:


<div class="row wall">
    <template>
        <div class="col-md-3 col-sm-6">
            <img src="{src}" class="img-responsive img-thumbnail">
        </div>
    </template>
</div>

With jQuery, we’re going to grab the entire template element (including its children), turn it into a string, replace {src} with the uploaded image, then add it into the DOM / our website. This might sound crazy, but it is really easy with jQuery:


    var template = $('template').html();
    var imageBlock = template.replace(/{src}/g, blob.url);
    $('.wall').prepend(imageBlock);

And now here it is all together:


$('#big-freaking-button').click(function() {

        // Settings
        filepicker.pick({
        mimetype: 'image/*', /* Images only */
        maxSize: 1024 * 1024 * 5, /* 5mb */
        imageMax: [1500, 1500], /* 1500x1500px */
        cropRatio: 1/1, /* Perfect squares */
        services: ['*'] /* From anywhere */

    }, function(blob) {

        // Returned stuff for example
        var filename = blob.filename;
        var url = blob.url;
        var id = blob.id;
        var isWriteable = blob.isWriteable;
        var mimetype = blob.mimetype;
        var size = blob.size;

        // Save to a database somewhere
        // Alternatively you can have filepicker do it for you: https://www.filepicker.com/documentation/storage/
        $.ajax({
            url: '/api/links',
            type: 'POST',
            data: {
                url: blob.url
            },
            success: function(data) {

                // Add it to the wall!

                // Quick and dirty template system
                var template = $('template').html();
                var imageBlock = template.replace(/{src}/g, blob.url);
                $('.wall').prepend(imageBlock);


            }
        });

    });

});

Populating the Wall on Page Load

Now that we can populate the wall of images on upload in near real-time, we’ll now populate the wall with all previous images. From the database of our uploaded URLs that we created, we’ll now fetch those.


$(function() {
    // Populate the wall!
    $.ajax({
        url: '/api/links',
        type: 'GET',
        success: function(data) {
            
            // Quick and dirty custom jQuery templating
            var template = $('template').html();

            // Loop through all URLs and add to wall
            $.each(data, function(index, value) {
                var imageBlock = template.replace(/{src}/g, value.url);
                $('.wall').prepend(imageBlock);
            });

        }
    });
});

That’s it! Now we have are fully working application with Filepicker!

Additional Examples

If you need a more stripped-down example to get you started, you can checkout these examples provided by Filepicker on JSFiddle:

Conclusion

Filepicker is an awesome tool for taking the pain out of file uploads. In this simple tutorial we were able to build a quick application to let users upload images from tons of third-party sources, be completely responsive, and display the result in the browser in near real-time.

We’ll also be releasing a Filepicker Angular Directive and tutorial soon. Keep checking the blog for when we release that.

Finally, here are some helpful links to wrap-up: