How to Upload Files Using JavaScript

In this lesson, we are going to cover how to upload files to the server using the multipart/form-data encoding, which we discussed in the previous lesson.

Updated database and model

First, you need a new structure for our users table. Since we haven't discussed how to run database migrations yet, let's delete our old database.sqlite and create a new one.

Next, add a new picture column in our users table.

models/user.js

javascript
1db.serialize(() => {
2  db.run(
3    `CREATE TABLE IF NOT EXISTS users (
4      id INTEGER PRIMARY KEY AUTOINCREMENT,
5      username TEXT,
6      email TEXT,
7      picture TEXT
8    )`
9  );
10});

You should know that the database cannot store the actual image file. The files should be saved inside the server's file system, and this picture column will simply store the path to the image file.

The corresponding create() method will become:

javascript
1static create(username, email, filePath, callback) {
2  const sql = "INSERT INTO users (username, email, picture) VALUES (?, ?, ?)";
3  db.run(sql, [username, email, filePath], function (err) {
4    callback(null, this.lastID);
5  });
6}

New form

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉