Guides

How to create an HTML contact form with file upload to Amazon S3 | Step-by-step guide

How to create an HTML contact form with file upload to Amazon S3 using Node.js and Express.js

How to create an HTML contact form with file upload to Amazon S3 | Step-by-step guide
On this page10 sections
  1. Prerequisites for the tutorial
  2. Steps we are going to follow
  3. Let's create a simple contact form using HTML
  4. Bootstrap an Express.js app
  5. Uploading File
  6. Let's try it
  7. Saving the messages to the MongoDB (Optional)
  8. Saving the form message
  9. Let's try it
  10. Alternative and Simple Way: Use formcarry

In this tutorial, we are going to create a sample app using Express.js to upload files to Amazon S3, then we are going to save our submission to the MongoDB

Prerequisites for the tutorial#

I don't want to cover some things that would over-complicate this tutorial, therefore I assume you know how to:

  • Get your API keys from Amazon AWS
  • Create a bucket on Amazon S3

If you don't know how to do that, you can take a look at this blog post, it's fairly simple to follow.

Steps we are going to follow#

  • Create a Contact Form using HTML
  • Bootstrap an Express.js app
  • Parsing form data
  • Uploading the file to S3
  • Saving the data to MongoDB

Let's create a simple contact form using HTML#

The key things when creating an upload form are the attributes you defined in <form>.

Let's create a simple form:

HTML
1<form action="#" method="POST">
2    <label for="email">Email Address</label>
3    <input type="email" id="email" name="email">
4
5    <label for="fullName">Full Name</label>
6    <input type="text" id="fullName" name="fullName">
7
8    <label for="message">Message</label>
9    <textarea name="message" id="message"></textarea>
10
11    <label for="photo">Photo</label>
12    <input type="file" id="photo" name="photo">
13
14    <button type="submit">Submit</button>
15</form>

We have built free form generator tool that you can customize and get HTML code, make sure you check it out if you need form template.

In the software world, most of the configurable options have a default value that will apply unless you override it, and one of these for form is enctype.

When you make an request to the backend, you have to encode the form data, there are 3 options available for enctype:

  • application/x-www-form-urlencoded (default)
  • multipart/form-data
  • text/plain

Through the w3 specification;

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters.
The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

Also unless you really know what you are doing, do not ever use text/plain (click here for why.)

So what we want to do is set enctype to multipart/form-data

Diff
- <form action="#" method="POST">
+ <form action="#" method="POST" enctype="multipart/form-data">
	<label for="email">Email Address</label>
    <input type="email" id="email" name="email">

    <label for="fullName">Full Name</label>
    <input type="text" id="fullName" name="fullName">

    <label for="message">Message</label>
    <textarea name="message" id="message"></textarea>

    <label for="photo">Photo</label>
    <input type="file" id="photo" name="photo">

    <button type="submit">Submit</button>
</form>

Now we have a simple contact form that's ready to send data to our express app that we're going to develop now. Let's save this to somewhere for now.

Bootstrap an Express.js app#

I assume that you've already installed Node.js.
Let's create and directory for our application using terminal/bash

create the directory my-app and views to store our contact form, then get into the directory
$ mkdir my-form my-form/views
$ cd my-form

Use the npm init command to initialize our project.

initialize the project
$ npm init

Just hit enter for everything, and install express.js using:

install express.js and save it to the package.json
$ npm install express express-fileupload --save
$ npm install nodemon -g

Now we have a directory structure like this:

directory tree of our project
.
|____my-form
| |____package.json
| |____views

Save the form that we created in the beginning under the views folder as form.html

directory tree (again) of our project
.
|____my-form
| |____index.js
| |____package.json
| |____views
| | |____form.html

Let's create our index.js:

index.js
1const express = require('express')
2const app = express()
3const fileUpload = require('express-fileupload')
4
5app.use(fileUpload({
6  // 50mb file limit
7  limits: { fileSize: 50 * 1024 * 1024 },
8  abortOnLimit: true
9}));
10
11app.get('/', (req, res) => {
12  res.sendFile('views/form.html' , { root : __dirname});
13})
14
15// endpoint that will handle the form
16app.post('/submit', (req, res) => {
17  const {body, files} = req
18  res.send({body, files})
19})
20
21const port = 3031
22
23app.listen(port, () => {
24  console.log(`Application is available at http://localhost:${port}`)
25})

Save it, then open the form.html and point the form to the /submit endpoint we just created with express app:

form.html
- <form action="#" method="POST" enctype="multipart/form-data">
+ <form action="/submit" method="POST" enctype="multipart/form-data">

Don't have much time for a form?#

File upload is not something you can achieve instantly, so if you want to have a quick and simple solution, check out our other blog post.

How to create a file upload form with formcarry in 5 stepsLearn how to create a file upload ready HTML form in 5 steps, super simple!/blog/how-to-create-a-file-upload-form/

how to create a file upload form with formcarry


Now let's add some style:

form.html
1<!DOCTYPE html>
2<html lang="en">
3<head>
4  <meta charset="UTF-8">
5  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6  <title>Contact Form</title>
7  <link href="https://fonts.googleapis.com/css2?family=Inter&display=swap" rel="stylesheet">
8  <style>
9    body {
10      font-family: "Inter";
11    }
12
13    label, button {
14      font-size: 16px;
15      cursor: pointer;
16    }
17
18    input, textarea {
19      border: 3px solid #eee;
20      padding: .4em 1em;
21      border-radius: 6px;
22    }
23
24    form {
25      display: grid;
26      grid-row-gap: 10px;
27      justify-content: center;
28    }
29
30    button {
31      margin-top: 10px;
32      background: #133EF5;
33      color: #fff;
34      padding: 10px 0;
35      border: 0;
36      border-radius: 6px;
37    }
38  </style>
39</head>
40<body>
41  <form action="/submit" method="POST" enctype="multipart/form-data">
42    <label for="email">Email Address</label>
43    <input type="email" id="email" name="email">
44
45    <label for="fullName">Full Name</label>
46    <input type="text" id="fullName" name="fullName">
47
48    <label for="message">Message</label>
49    <textarea name="message" id="message"></textarea>
50
51    <label for="photo">Photo</label>
52    <input type="file" id="photo" name="photo">
53
54    <button type="submit">Submit</button>
55  </form>
56</body>
57</html>

Finally run:

Bash
$ nodemon index.js

Then visit http://localhost:3031 from your browser:

form.html
form.html

Fill out the form with sample data and file then submit.
You will see something like this:

Browser showing the JSON response from /submit with the body fields and the details of the uploaded file
sorry Peter, 404 not found 🥺

use JSONView Chrome Extension to display JSON content like 👆

Great, now we are ready to do the rest, let's clarify something before getting going:

The name attributes in form.html joined by arrows to the matching keys in the JSON response
how your data transmitted to the backend application

As you can see with the picture above, whatever you define for name will be present on the backend with same value, so if you don't name your fields then you can't parse them.
This is an common mistake so be careful 🕵️

Configuring AWS-SDK#

Let's install aws-sdk:

Bash
$ npm install aws-sdk --save

Then import it and use the keys that you have obtained from AWS:

Replace your access key, secret key and bucket name
const express = require('express')
const app = express()
const fileUpload = require('express-fileupload')
+ const AWS = require('aws-sdk')

+ AWS.config.update({
+  accessKeyId: '<Replace with your access key>',
+  secretAccessKey: '<Replace with your secret key>'
+ })

+ const s3 = new AWS.S3({ params: { Bucket: '<Replace with your bucket name>' }});

app.use(fileUpload({
  // 50mb file limit
  limits: { fileSize: 50 * 1024 * 1024 },
  abortOnLimit: true
}));

app.get('/', (req, res) => {
  res.sendFile('views/form.html' , { root : __dirname});
})

app.post('/submit', (req, res) => {
  const { body, files } = req
  res.send({body, files})
})

const port = 3031

app.listen(port, () => {
  console.log(`Application is available at http://localhost:${port}`)
})

Uploading File#

We are ready to upload now, first let's transform our function to an async function:

index.js
- app.post('/submit', (req, res) => {
+ app.post('/submit', async (req, res) => {

Then let's add the code that manages upload:

Upload the file to the Amazon S3 | index.js
1app.post('/submit', async (req, res) => {
2  const { files } = req
3
4  try {
5    const upload = new AWS.S3.ManagedUpload({
6      params: { 
7        // pass directly the buffer string
8        Body: files.photo.data, 
9        // pass the file name
10        Key: files.photo.name,
11        // make it public
12        ACL: 'public-read'
13      },
14      // use the const s3 that we defined above
15      service: s3,
16    })
17
18    const response = await upload.promise()
19
20    res.send(response)
21  } catch (error) {
22    res.send(error)
23  }
24})

So what's happening there?#

We destructured the req object that holds the files, so const files is equivalent of req.files.
Let's remember our test payload.

The test payload again: the body fields and the details of the photo file in the JSON response

Everything under files key is provided by express-fileupload module, which handles the files and returns them in a nice and usable structure.

AWS.S3.ManagedUpload and AWS.S3.Upload can accept Buffer, Typed Array, Blob, String, ReadableStream. While our files.photo.data is a Buffer we can directly pass that to the Body parameter .

ACL is shorthand for Access Control List, which we've set to public-read to view the uploaded file.

Key is the name of our file.

Let's try it#

Visit http://localhost:3031/ and fill out the fields. You don't necessarily have to fill anything other than the file because we haven't done anything with it yet.

After you click the Submit button, you will see something like this:

JSON response from Amazon S3 with the ETag, Location, Key and Bucket of the uploaded file
Uploaded File

Then check your bucket and you will see the file in the bucket.

Amazon S3 bucket listing that shows the uploaded uncle_ben.jpg file
S3 Dashboard

It worked! Now we have form data and the uploaded file details, we can use this data to save to the database or send some webhook.

Renaming the files#

It's not a wise choice to use the original file name, in case someone else uploads a file with the same name, it's better to write a simple function to generate a random name:

random name generator
1const path = require('path');
2
3const generateUniqueFileName = (fileName) => {
4  const extension = path.extname(fileName)
5  const date = Date.now();
6
7  let randomHash = ''
8  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
9  
10  new Array(20).fill(null).map(_ => {
11    randomHash += characters.charAt(Math.floor(Math.random() * characters.length));
12  })
13
14  return `${randomHash}-${date}${extension}`
15}

It's not even a wise choice to depend on only a random generated string: it's better to add something unique to that time, like time ⏱ itself using Date.now();

it will output something like => cm0avQtXfOAo1PEdJxZZ-1602531725730.jpg
const upload = new AWS.S3.ManagedUpload({
  params: { 
    // pass directly the buffer string
    Body: files.photo.data, 
    // pass the file name
-   Key: files.photo.name,
+   Key: generateUniqueFileName(files.photo.name),
    // make it public
    ACL: 'public-read'
  },
  // use the const s3 that we defined above
  service: s3,
})

Saving the messages to the MongoDB (Optional)#

Now, because we have the file and form message, we can save them into the database.
I'm going to use MongoDB for this purpose. I assume that you have a working MongoDB setup; if you don't you can checkout this page

I'm going to use mongoose npm package in order to do the operations inside our express.js app

Install Mongoose#

Install mongoose using npm
$ npm install mongoose --save

Create A MongoDB Database#

Create contactform database using Mongo CLI
$ mongo
$ use contactform

Import Mongoose#

Add this code to index.js

index.js
const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost:27017/contactform');

Create Model#

First let's create a directory called models under our project root, than create form.js into it

create models directory and models/form.js
mkdir models
touch models/form.js

Open the empty form.js using your code editor, and paste this:

our form model
const mongoose = require('mongoose');

const form = new mongoose.Schema({
  fullName: String,
  email: String,
  message: String,
  photo: String,
});

module.exports = mongoose.model('form', form);

Models are basically MongoDB Schema on steroids - you can take a look at them here to learn more. All of the fields I defined are the fields we have in our form.html

Import our Model#

Let's import our model into the index.js

index.js
const mongoose = require('mongoose')

mongoose.connect('mongodb://localhost:27017/contactform');

+ const Form = require('./models/form')

Saving the form message#

Let's change our main route for saving the submission:

Saving submission to our form model
app.post('/submit', async (req, res) => {
  const { files } = req

  try {
    const upload = new AWS.S3.ManagedUpload({
      params: { 
        // pass directly the buffer string
        Body: files.photo.data, 
        // pass the file name
        Key: generateUniqueFileName(files.photo.name),
        // make it public
        ACL: 'public-read'
      },
      // use the const s3 that we defined above
      service: s3,
    })

    const response = await upload.promise()

+    const { fullName, email, message } = req.body
+    const submission = new Form({
+      fullName: fullName,
+      email: email,
+      message: message,
+      photo: response.Location
+    })

+    submission.save()

-    res.send(response)
+    res.send(submission)
  } catch (error) {
    res.send(error)
  }
})

Little trick#

While the key and the value are same we can convert our code to this:

JavaScript
const submission = new Form({
  fullName,
  email,
  message,
  photo: response.Location
})

Let's try it#

Visit https://localhost:3031 and fill the fields

Contact form in the browser filled in with an email address, a name, a message and a photo

Click Submit, then:

JSON response with the saved submission, including the Amazon S3 URL of the photo

That's it! now you have a perfectly functional form.


Alternative and Simple Way: Use formcarry#

By no means all of those process are time consuming stuff, we have an offer for you, feel free to try formcarry - form backend, instead of coding everything on your own you can have a file upload ready form in under a minute just by changing your form's action attribute

HTML
1<form action="https://formcarry.com/s/{YOUR_FORM_ID}" method="POST" enctype="multipart/form-data">
2    <label for="email">Email Address</label>
3    <input type="email" id="email" name="email">
4
5    <label for="fullName">Full Name</label>
6    <input type="text" id="fullName" name="fullName">
7
8    <label for="message">Message</label>
9    <textarea name="message" id="message"></textarea>
10
11    <label for="photo">Photo</label>
12    <input type="file" id="photo" name="photo">
13
14    <button type="submit">Submit</button>
15  </form>

Comparing the steps above, formcarry is a very fast and secure way to collecting submissions with file attachments, use it in your contact forms, job application forms, or event forms as you need.

Grab your Form ID from here for free!

Nusu AlabugaFounder, formcarry

Nusu Alabuga founded formcarry in 2017 and still runs it: the ingest pipeline, the spam filtering, the email delivery and the incident tracking that watches customers' forms. A product engineer by trade, with years of work in payments, security, invoicing and banking infrastructure.

WebsiteXLinkedInGitHub

Keep reading

LET'S GET STARTED!

Hassle Free Forms

Create your form endpoint and start collecting submissions

for your HTML forms, it only takes 2 minutes to set up your form

formcarry dashboard.
Your email address|