Below is the module to upload single file to server using express.js
var express = require('express')
var route1 = express.Router()
var multer = require('multer') // required package to read multipart from data
var upload = multer({
dest: "./files"
}) // we can get more control using storage option (filename, destination functions supported)
route1.use('/', express.static(__dirname + '/files')); // not necessary to upload only. but necessary to server files
// below is post handler. multer supports three type of uploads := single, array, fields
// in the following post handler we are using single method of multer object which searches
// for 'filename' input.
route1.post('/', upload.single('filename'), function(req, res, next) { // next is not necessary . But you may want further processing
res.send("done");
})
route1.get('*', function(req, res) { // serve upload page when get request is sent
res.render("upload"); // template to render
})
module.exports = route1
How to Use:
- Create a main.js file (main in you package.json file)
- Insert following code
var express = require('express')
var app = express()
var route = require('./uploader.js') // uploader.js contains above module
app.use('/upload', route) // define the url of upload.js route
app.set('view engine', 'pug') // view rendering engine.
app.set('views', './views') // folder containing .pug files for rendering
app.listen(80);
- Now create a template file in your views folder with name ‘upload.pug’. For more on pug visit https://pugjs.org/api/getting-started.html
doctype html
html
head
title Upload
body
form(name='FormName', enctype='multipart/form-data', action='/upload', method='post')
input(type='file', name='filename')
input(type='submit')
Your file will be stored under directory files with random name and without any extension. To give a specific name and filter the type of files allowed use storage option in multer upload object creation.