Uploading Images to a Node.js Backend Using Multer and Express
File uploads from the frontend are pretty much useless without an API on the backend to receive them and save them to a database, so here we are!
This post of ours goes over our Vue.js frontend setup.
Installation
First things first, prepare your Node.js project by installing the following packages if you don’t have them already:
$ npm install multer body-parser express morgan crypto --save
Here’s a quick breakdown of what each of these packages do:
- Multer: Our image upload library. It handles getting formdata from requests
- Body-parser: Extracts the entire body portion of an incoming request stream and exposes it on
req.body
as something easier to interface with. More here - Express: The very popular web framework that sits on top of Node.js
- morgan: Express middleware for logging network requests
- crypto: Deals with cryptography, and has a wide range of other functions, some of which you’ll see here
Setting up the project
Having added all the necessary modules, we can proceed to setup Multer like this:
const storage = multer.diskStorage({
destination: 'some-destination',
filename: function (req, file, callback) {
//..
}
});
- destination: Indicates where you want to save your files
- filename: Indicates how you want your files named. Multer doesn’t add extensions to file names, so you have to take care of that on your own. Using crypto, you can generate a random 16 character string and attach the extension using
path
:
crypto.pseudoRandomBytes(16, function(err, raw) {
if (err) return callback(err);
callback(null, raw.toString('hex') + path.extname(file.originalname));
});
Next, setup your Express middleware. The code should be fairly simple to understand:
//...
import bodyParser from 'body-parser';
import morgan from 'morgan';
import express from 'express';
const app = express();
//..
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(morgan('dev'));
We’re almost there! Prepare your route to receive the file:
app.post('/', upload.single('avatar'), (req, res) => {
if (!req.file) {
console.log("No file received");
return res.send({
success: false
});
} else {
console.log('file received');
return res.send({
success: true
})
}
});
When an image is received by the route, it will be automatically saved by multer to the directory you previously specified. The
upload.single
call is handled by the multer middleware.
You can then acquire the file’s name like so
const host = req.host;
const filePath = req.protocol + "://" + host + '/' + req.file.path;
// ...save filePath to database
One last thing, though: In order to serve your pictures using express, ensure you make the project directory static. For instance:
app.use(express.static(__dirname, 'public'));
0 comentarios:
Publicar un comentario