Codementor Events

Saving Costs on AWS with Data Classification

Published May 31, 2022Last updated Dec 25, 2022
Saving Costs on AWS with Data Classification

Adding file upload to your website can be tricky. There are several aspects to take care of, including:

  • The file upload interface users interact with to select files for upload.
  • Handling file upload on the server side.
  • Ensuring high performance for upload and later on, delivery of files to users.
  • Ensuring your server has enough storage to handle expected user uploads over time.
  • Performing transformations on uploaded files—for example, if the file is an image, there might be a need to scale it to a certain size or convert it to another format.
  • Ensuring file upload is highly secure to prevent users from uploading malicious files, and avoid abuse such as uploading too many files.
    Integrating with services like Google Drive, Dropbox, and social media channels to make it more convenient for users to upload their files.

While you can build a basic JavaScript file upload script yourself in only a few minutes, it will handle only a few of the above concerns. Therefore, it is a good idea to check out managed file upload services. These come at a cost, but they provide an end-to-end solutionhttpsno upload files, to cloud-based storage, fast delivery, security, and file transformations.

In this article, I’ll cover three popular options for file upload in JavaScript: Cloudinary, Upload.js, and Filepond.

JavaScript File Upload with Cloudinary

Cloudinary is a cloud-based media management service. It allows you to upload images to cloud storage and perform a large variety of transformations on them, including image optimizations and format conversions, without changing the base images.

Cloudinary provides a free, fully functional file upload widget. Files are securely uploaded to cloud storage, with automated backups and revision history. Another nice feature is the ability to let users upload images directly from Instagram, Shutterstock, Google Drive, Dropbox, Facebook account, or any remote URL.

Cloudinary offers a free tier that lets you store up to 75,000 images and videos weighing a total of 2 GB. The free tier also includes 7,500 image transformations and 5 GB viewing bandwidth per month.

Cloudinary lets you set up file upload in three steps:

Step 1: Creating an HTML button element

Instead of creating an entire HTML form, you can just add the following line of code to the <body> tag of your HTML document:

<button id="upload_widget" class="cloudinary-button">Upload files</button>

Step 2: Add JavaScript

Copy the following JavaScript code to the page:

<script src="https://widget.cloudinary.com/v2.0/global/all.js" type="text/javascript"></script>
<script type="text/javascript">  
  var widget = cloudinary.applyUploadWidget({ 
    cloudName: 'demo', 
    uploadPreset: 'blog_upload' }, 
    (error, result) => { 
       if (!error && result && result.event === "success") { 
      		console.log('Done uploading..: ', result.info); 
   	      }

     });    

document.getElementById("upload_widget").addEventListener("click", function(){
    myWidget.open();
  }, false);
</script>

Step 3: Define Cloudinary upload settings

  • Sign up for a free Cloudinary account
  • Log in to the dashboard and take note of your cloudName, API Key and API Secret.
  • Create an upload preset that defines how files will be uploaded from your upload widget. Use your cloudName and credentials where appropriate.

The file upload form should now be functional. It will look like this:
unnamed.png

Image Source: Cloudinary

JavaScript File Upload with Upload.js

Upload provides an infrastructure that lets you easily add file upload functionality to applications. It is a SaaS offering that includes file storage, file transformation, and file hosting functionality.

The Upload solution’s client-side library is called Upload.js. This is a JavaScript file upload library with no dependencies, which comes integrated with the Upload API.

Step 1: Add Upload.js to head tag
Include Upload.js in the <head> tag of your web page, like this:

  <script src="https://js.upload.io/upload-js/v1"></script>

Step 2: Add initialization code
Also in the <head> tag, below the Upload.js script, add the following code:

<script>
    const onFileSelected =
      new Upload({ apiKey: "YOUR_API_KEY_HERE" }).createFileInputHandler({
        onUploaded: ({ fileUrl, fileId }) => {
<script>
    const onFileSelected =
      new Upload({ apiKey: "YOUR_API_KEY_HERE" }).createFileInputHandler({
        onUploaded: ({ fileUrl, fileId }) => {

           // -----------------------------------------
           // File successfully uploaded to upload.io!
           // -----------------------------------------
           // Send the file ID to your API, for example,
           // to set it as the profile picture for a user.
           // -----------------------------------------
          console.log(`File uploaded to: ${fileUrl}`);

        }
      });
  </script>
  ...
</head>

Step 3: Add upload button to your page
In the <body> tag of your page, add this line of code:

<input type="file" onchange="onFileSelected(event)" />

Your page will now display a file upload form. When the user uploads a file, Upload will provide a fileId. You can construct a URL to your files at any time using this format:

https://upcdn.io/AYU81093TgPQauaR
                        \____File ID___/
\_______________File URL_______________/

File Upload with FilePond

FilePond is a JavaScript library that can upload files, optimize images for faster uploads, and offers a smooth user experience. Unlike the other solutions in this post, FilePond does not integrate with cloud storage—it is a library that uploads files directly to your web server.

FilePond allows users to upload files, entire directories, blobs, local URLs, remote URLs, and Data URIs. It supports asynchronous upload using AJAX, chunked uploads, and base64 data encoding. Other useful features are automated image optimization, resizing, cropping, and filtering.

Like the other solutions we covered, FilePond provides a responsive file upload form, which is functional on mobile and desktop devices.

Step 1: Installing FilePond
You can install FilePond using NPM (if you are using Node.js), directly from a CDN, or by manually loading the files from GitHub. We’ll show the easiest way—via CDN.

Include the following code in the <head> element of your page to load FilePond from CDN:

<link href="https://unpkg.com/filepond@^4/dist/filepond.css" rel="stylesheet" />

And include this script in the <body> tag of your page:

<script src="https://unpkg.com/filepond@^4/dist/filepond.js"></script>

2. Create file upload form
Add the following line to the <body> element of your page. This is just a placeholder for the form, it will be replaced by FilePond in the next step:

<input type="file" />

3. Activate the file upload form
Add the following JavaScript code to invoke the create() method on the FilePond library, to create a “drop area” that allows users to upload their files.

<script>
    const inputElement = document.querySelector('input[type="file"]');
    const pond = FilePond.create(inputElement);
</script>

Conclusion

In this article, I explained basic requirements for JavaScript file upload and presented three solutions that can help you provide a good experience for users without working hard:

  • Cloudinary lets you add a file upload widget to your pages with only a few lines of code, and takes care of cloud-based storage, CDN delivery, and file transformations.
  • Upload.js also provides a convenient upload widget and manages cloud-based storage for your files. Like Cloudinary, it provides a CDN, but has less extensive file transformations.
  • FilePond is not a fully managed service like the others, and is also provided free. It is a JavaScript library you can use to implement file upload with multiple options, but you still need to handle storage and other aspects on your own.

I hope this will be useful as you add a great file upload experience to your website or web application.

Discover and read more posts from Gilad David Maayan
get started
post commentsBe the first to share your opinion
Show more replies