Skip to content

Instantly share code, notes, and snippets.

@fsojitra
Last active November 20, 2017 14:13
Show Gist options
  • Save fsojitra/cec7c5b6b4243297f1e1c228d1c18fac to your computer and use it in GitHub Desktop.
Save fsojitra/cec7c5b6b4243297f1e1c228d1c18fac to your computer and use it in GitHub Desktop.
code to upload file to the server with extension using express.js and multer
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form method="post" enctype="multipart/form-data"><input type="text" name="a">
<input id="file" type="file" name="photo" />
<button type="submit">test</button>
</form>
</body>
</html>
var express = require('express');
var multer = require('multer');
var path = require('path');
// this will upload file to your server with extension
var upload = multer({storage: multer.diskStorage({
destination: function (req, file, callback)
{ callback(null, './uploads');},
filename: function (req, file, callback)
{ callback(null, file.fieldname + '-' + Date.now()+path.extname(file.originalname));}
})
})
var app = express();
app.get('/', function(req, res){
res.render('index.ejs');
});
// accept one file where the name of the form field is named photo
app.post('/', upload.single('photo'), function(req, res){
console.log(req.body); // form fields
console.log(req.file); // form files
res.send('photo uploaded!')
});
app.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment