Every project requires file storage capabilities, such as storing images, PDFs, CSVs, XLS files, and other assets in the cloud. I utilize DigitalOcean Spaces, which operates using the AWS S3 SDK. Let me demonstrate how to create an API endpoint for uploading assets.

  1. Setup API route in server.js and create a file bucketRoutes.js in routes folder.

JavaScript

Copy
// Import the route file on the top const bucketRoutes = require('./app/routes/bucketRoutes'); // bind the bucketRoutes to **/bucket** path app.use('/bucket', bucketRoutes);
  1. bucketRoutes.js file looks like this.

JavaScript

Copy
// app/routes/bucketRoutes.js const express = require('express'); const router = express.Router(); const bucketController = require('../controllers/bucketController'); router.post('/upload', bucketController.uploadFile); module.exports = router;
  1. Create bucketController.js file in the controllers folder.

JavaScript

Copy
// app/controllers/bucketController.js const { responseList } = require('../errors/responseList'); const path = require('path'); const { slugify } = require('../helpers/functions'); const s3 = require('../clients/s3'); exports.uploadFile = async function (req, res, next) { const { acl, folderName } = req.body; try { const [key, value] = Object.entries(req.files)[0]; const fileExt = path.extname(value.name); let pathWhereFileWillStore = `${slugify(value.name)}${fileExt}`; if (folderName) { pathWhereFileWillStore = `${folderName}/${slugify(value.name)}${fileExt}`; } let params = { Bucket: process.env.SPACE_BUCKET_NAME, Body: value.data, Key: pathWhereFileWillStore, ACL: 'public-read', ContentType: value.mimetype, }; if (acl) params.ACL = acl; s3.upload(params, async function (err, data) { if (err) return res.status(500).send(responseList(500, err.message)); res.send(data); }); } catch (error) { res.status(400).send(responseList(400, error.message)); } };