How to insert and retrieve video from mongodb in node js - node.js

I new to mean stack. I want to upload video to mongodb and then I want to retrieve it.
this is app.js file
`const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const crypto = require('crypto');
const mongoose = require('mongoose');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override');
const app = express();
// Middleware
app.use(bodyParser.json());
app.use(methodOverride('_method'));
app.set('view engine', 'ejs');
// Mongo URI
const mongoURI = 'mongodb://fawad:Fawad123#ds155243.mlab.com:55243/imageupload';
// Create mongo connection
const conn = mongoose.createConnection(mongoURI);
// Init gfs
let gfs;
conn.once('open', () => {
// Init stream
gfs = Grid(conn.db, mongoose.mongo);
gfs.collection('uploads');
});
// Create storage engine
const storage = new GridFsStorage({
url: mongoURI,
file: (req, file) => {
return new Promise((resolve, reject) => {
crypto.randomBytes(16, (err, buf) => {
if (err) {
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
const fileInfo = {
filename: filename,
bucketName: 'uploads'
};
resolve(fileInfo);
});
});
}
});
const upload = multer({ storage });
// #route GET /
// #desc Loads form
app.get('/', (req, res) => {
gfs.files.find().toArray((err, files) => {
// Check if files
if (!files || files.length === 0) {
res.render('index', { files: false });
} else {
files.map(file => {
if (
file.contentType === 'video/mp4' ||
file.contentType === 'video/webm '
) {
file.isVideo = true;
} else {
file.isVideo = false;
}
});
res.render('index', { files: files });
}
});
});
// #route POST /upload
// #desc Uploads file to DB
app.post('/upload', upload.single('file'), (req, res) => {
// res.json({ file: req.file });
res.redirect('/');
});
// #route GET /files
// #desc Display all files in JSON
app.get('/files', (req, res) => {
gfs.files.find().toArray((err, files) => {
// Check if files
if (!files || files.length === 0) {
return res.status(404).json({
err: 'No files exist'
});
}
// Files exist
return res.json(files);
});
});
// #route GET /files/:filename
// #desc Display single file object
app.get('/files/:filename', (req, res) => {
gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
// Check if file
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
// File exists
return res.json(file);
});
});
// #route GET /image/:filename
// #desc Display Image
app.get('/video/:filename', (req, res) => {
gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
// Check if file
if (!file || file.length === 0) {
return res.status(404).json({
err: 'No file exists'
});
}
// Check if image
if (file.contentType === 'video/mp4' || file.contentType === 'video/webm') {
// Read output to browser
const readstream = gfs.createReadStream(file.filename);
readstream.pipe(res);
} else {
res.status(404).json({
err: 'Not an image'
});
}
});
});
// #route DELETE /files/:id
// #desc Delete file
app.delete('/files/:id', (req, res) => {
gfs.remove({ _id: req.params.id, root: 'uploads' }, (err, gridStore) => {
if (err) {
return res.status(404).json({ err: err });
}
res.redirect('/');
});
});
const port = 9000;
app.listen(port, () => console.log(`Server started on port ${port}`));
`
index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<style>
video {
width: 100%;
}
</style>
<title>Mongo File Uploads</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 m-auto">
<h1 class="text-center display-4 my-4">Mongo File Uploads</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="file" name="file" id="file" class="custom-file-input">
<label for="file" class="custom-file-label">Choose File</label>
</div>
<input type="submit" value="Submit" class="btn btn-primary btn-block">
</form>
<hr>
<% if(files){ %>
<% files.forEach(function(file) { %>
<div class="card card-body mb-3">
<% if(file.isVideo) { %>
<video src="video/<%= file.filename %>" alt="">
<% } else { %>
<%= file.filename %>
<% } %>
<form method="POST" action="/files/<%= file._id %>?_method=DELETE">
<button class="btn btn-danger btn-block mt-4">Delete</button>
</form>
</div>
<% }) %>
<% } else { %>
<p>No files to show</p>
<% } %>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN"
crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
</body>
</html>
this code work for image..when I used (file.contentType = image/png).
but for video it's not working.. is Image and video upload are same?

You can use Formidable. As It support multipart data. And for retrieve video you can use fs(file system)

Actually you don't save media(image or video) in DB, you store it in some storage drive(locally or cloud) like s3 bucket, and then store its location url in your DB.
and this code might be helpful.
saveImage(urlPath, folderPath, multiple) {
return new Promise((resolve, reject) => {
var timestamp = Date.now();
var filepath = urlPath;
var imageUrl;
var ext = path.extname(filepath || '').split('.');
var extension = ext[ext.length - 1];
var tmp_path = filepath;
imageUrl = folderPath + timestamp + '.' + extension;
if (multiple != '' && multiple != undefined) { imageUrl = folderPath + timestamp + multiple + '.' + extension; }
var target_path = __dirname + '/../' + imageUrl;//Change according to your location.
console.log("target_path", target_path);
mv(tmp_path, target_path, { mkdirp: true }, function (err) { })
return resolve({ status: 1, url: imageUrl });
})
}
Now, urlPath is your media path, foldarPath is path where you want to store your media and multiple is to give unique name.
you can call this method like this.
var multiple = Number(0) + Number(10);
console.log("multiple", multiple);
var saveImage = await 'YOUR_FILE_NAME'.saveImage(files.photo[0].path, 'public/Image/', multiple);
console.log(saveImage);

<video src="video/<%= file.filename %>" controls alt="">
//Try adding the controls command in the video tag. It helps the video run.

Related

response.writeHead(302) in NodeJS not redirecting in async function callback

Below is a snippet of my NodeJS server code.
async function handleLoginReq(req, res) {
let queryDB = `
SELECT password FROM faculty_information
WHERE email='${userInfo["user-email"]}';
`;
try {
const dbres = await client.query(queryDB);
if (dbres.rows.length !== 0) {
if (dbres.rows[0].password === '') {
const errVal = 'Please register yourself correctly';
res.writeHead(302, {
'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}`
});
res.end();
client.end();
} else if (userInfo["user-password"] === dbres.rows[0].password) {
res.writeHead(302, {
'Location': '/experiment_page/index.html'
});
res.end();
client.end();
} else {
const errVal = 'Incorrect password or email address';
res.writeHead(302, {
'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}`
});
res.end();
client.end();
}
} else {
const errVal = 'Please sign up';
console.log(errVal);
res.statusCode(302);
res.setHeader('Location', `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}`)
//res.writeHead(302, { 'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}` });
res.end();
client.end();
}
} catch (err) {
res.writeHead(500);
res.end("Internal server error");
client.end();
}
}
handleLoginReq(req, res);
The client.query() function is a asynchronous function. However, none of the res.writeHead(302)'s are working inside the callback of this function. A res.writeHead(302) does work if I add it below the function call of handleLoginReq(req, res);.
handleLoginReq(req, res);
// Below redirect works
res.writeHead(302, { 'Location': '/experiment_page/index.html' });
res.end();
The above code runs when a form is submitted on /login_page/loginPage.html.
Instead of redirecting the user to either /experiment_page/index.html or back to /login_page/loginPage.html?error=something with a URL parameter, it just reloads the page to /login_page/loginPage.html.
Below is the HTML for this page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/login_page/css/loginStyles.css">
<script src="/login_page/js/labelChange.js" defer></script>
<script src="/login_page/js/redirectSignUp.js" defer></script>
<script src="/login_page/js/loginValidation.js" defer></script>
<title>DigiChit - The Online Chit System | Login</title>
</head>
<body>
<nav class="navbar">
<ul>
<li><h1>DigiChit</h1></li>
<li>Home</li>
<li>About</li>
</ul>
</nav>
<div class="login-info">
<form method="POST" class="form">
<img src="/images/avatar.png" id="avatar" alt="avatar">
<h2>Login</h2>
<div class="input-group">
<input type="email" name="user-email" id="user-email" required>
<label for="user-email">Email</label>
<span id="email-error"></span>
</div>
<div class="input-group">
<input type="password" name="user-password" id="user-password" required>
<label for="user-password">Password</label>
<span id="general-error"></span>
<button type="submit" class="submit-btn" id="login-button">Login</button>
<button type="submit" class="submit-btn" id="sign-up">SignUp</button>
Forgot Password?
</div>
</form>
</div>
</body>
</html>
None of the client side JS scripts are interfering with the process either. I did put console.log()'s in all of the other conditions, and there are no clashes either where many res.writeHead() are running simultaneously.
If anyone can find why this is happening?
I tried to use res.setHeader() and res.statusCode() instead of res.writeHead() to see if anything changed, and nothing happened. I tried using promises instead of async/await and that changed nothing either.
###################################
EDIT (Updated with async/await syntax)
###################################
Here is the server code snippet containing more info on where the function is located.
const server = https.createServer(options, async function (req, res) {
// For form submissions
if (req.method.toLowerCase() === "post") {
let body = '';
req.on("data", (chunk) => {
body += chunk.toString();
})
req.on("end", async function () {
// querystring.decode converts browser query string into an object
const userInfo = querystring.decode(body); // userInfo is an object here
// Status code 302 stands for code of redirection
if (req.url.startsWith("/login_page/loginPage.html")) {
const client = createClient();
await client.connect();
let errVal = "";
async function handleLoginReq(req, res) {
// Below is the query to get user password
let dbQuery = `
SELECT password FROM faculty_information
WHERE email='${userInfo["user-email"]}';
`;
try {
const dbres = await client.query(dbQuery);
if (dbres.rows.length !== 0) {
if (dbres.rows[0].password === '') {
const errVal = 'Please register yourself correctly';
res.writeHead(302, { 'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}` });
res.end();
client.end();
} else if (userInfo["user-password"] === dbres.rows[0].password) {
res.writeHead(302, { 'Location': '/experiment_page/index.html' });
res.end();
client.end();
} else {
const errVal = 'Incorrect password or email address';
res.writeHead(302, { 'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}` });
res.end();
client.end();
}
} else {
const errVal = 'Please sign up';
console.log(errVal);
res.writeHead(302, { 'Location': `/login_page/loginPage.html?error=${encodeURIComponent(errVal)}` });
res.end();
client.end();
}
} catch (err) {
res.writeHead(500);
res.end("Internal server error");
client.end();
}
}
await handleLoginReq(req, res);

Login System in NodeJS & Excel

So, I am creating a basic system which runs a login system in nodejs and express using an Excel file as a base. The excel CSV file will have a list of username and passwords and I am reading it using fast-csv. But when it is authenticating with the listing, it is matching only the first record. Not the other records in the excel. Any clue why? Code is as below:
index.js file
var express = require('express');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var csv = require('fast-csv')
var fs = require('fs')
app.listen(80, function(){
console.log("Server is running")
})
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({extended : true}));
app.post("/", function (req,res) {
fs.createReadStream(path.resolve(__dirname, 'master_data.csv'))
.pipe(csv.parse({ headers: true}))
.on('error', error => console.error(error))
.on('data', row => {
if(req.body.username == row.username && req.body.password === row.password && row.loggedIn == 'FALSE'){
res.send("Login Successful. <br> Your link is available below:" + row.link)
}else{
res.send("Login Failed")
}
})
// Log file created below
var userSchema = {
Username: req.body.username,
loginDateTime: new Date().toString(),
ipAddress: req.ip,
};
fs.appendFile('logfile.txt', JSON.stringify(userSchema) + ",", function(err, file){
if(err) throw (err);
})
});
index.html file
<html>
<head>
<title>School Login Page</title>
<link rel="stylesheet" type="text/css" href="./css/mainCSS.css">
</head>
<body>
<h2>School Login Page</h2><br>
<p>Please enter all details exactly as per details provided to you.</p>
<form action="/" method="POST">
<label for="username">Username</label>
<input type="text" id="username" name="username" value="" required><br><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="submit" id="submitButton">
</form>
</body>
</html>
I also want to create an alert for a failed login but I know that you cannot create alerts server side in nodejs. How can I do this is in the front-end? Thanks
The data event is fired for each row of the CSV. What you want is to check the username and password against all present records.
To achieve this, change the following:
fs.createReadStream(path.resolve(__dirname, 'master_data.csv'))
.pipe(csv.parse({ headers: true}))
.on('error', error => console.error(error))
.on('data', row => {
if(req.body.username == row.username && req.body.password === row.password && row.loggedIn == 'FALSE'){
res.send("Login Successful. <br> Your link is available below:" + row.link)
}else{
res.send("Login Failed")
}
})
to:
let isValid = false, rowLink;
fs.createReadStream(path.resolve(__dirname, 'master_data.csv'))
.pipe(csv.parse({ headers: true}))
.on('error', error => console.error(error))
.on('data', row => {
if(req.body.username == row.username && req.body.password === row.password && row.loggedIn == 'FALSE'){
isValid = true;
rowLink = row.link
}
})
.on('end', () => {
if (isValid) {
res.send("Login Successful. <br> Your link is available below:" + rowLink)
} else {
res.send("Login Failed")
}
})

NodeJS Mongoose insert event to public/index.html

I'm learning nodejs and I have a project where I want users to post form data which then populates an html table located in public/index.html.
At the moment, I am writing the submitted data to a database collection using the following code:
const mongoose = require('mongoose')
const express = require('express');
const app = express();
const server = app.listen(3000);
app.use(express.json()); // for retrieving form data
app.use(express.static('public'));
mongoose.connect('mongodb://localhost/class', {useNewUrlParser: true})
.then( () => console.log('Connected to class database'))
.catch( () => console.error('Connection attempt to class database failed'))
const personSchema = new mongoose.Schema({
name: String,
date: {type: Date, default: Date.now}
})
const Person = mongoose.model('Person', personSchema)
app.post('/join_class', (req,res) => {
res.send('... joining class')
console.debug(req.body.name)
// document.getElementById('class_table').insertRow(req.body.name)
joinClass(req.body)
})
async function joinClass(data){
console.log(data)
person = new Person({
name: data.name
})
await person.save();
}
My problem is I need the same data to populate an HTML table located in my public/index.html but of course I don't have access to the document object in index.js. The index.html file is below:
<!DOCTYPE html>
<html lang="en">
<head>
<script src='https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.dev.js'></script>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- <script src="/client.js"></script> -->
<title>TestING</title>
</head>
<body>
<table id='class_table'>
<tr><th>Class</th></tr>
<tr><td>testing</td></tr>
</table>
</body>
</html>
So, how can I create a mongoDB event/alert such that when the post data is inserted into the database, the same data is made available to index.html where I CAN use the document object to populate the table?
Here's a example in which you can add new Person's and the list in the index.html page should update on a successful insert.
index.js
app.post('/join_class', (req, res) => {
var person = new Person({
name: req.body.name
});
person.save().then((data) => {
res.send(data);
}).catch((err) => {
res.status(500).send(err);
});
})
app.get('/class', (req, res) => {
Person.find({}).then((data) => {
res.send(data);
}).catch((err) => {
res.status(500).send(err);
});
})
index.html (body tag content)
<body>
<div>
Name:<br>
<input type="text" id="name" value="">
<br>
<button onclick="addPerson()">Add Person</button>
</div>
<br/>
<b>Person's in List: </b>
<ul id='class_table'>
</ul>
<script src="/client.js"></script>
</body>
client.js
function listPerson() {
var req = new XMLHttpRequest();
req.open("GET", '/class');
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var aList = JSON.parse(req.responseText),
list = document.getElementById("class_table");
list.innerHTML = "";
aList.forEach(e => {
var item = document.createElement("li");
item.innerHTML = e.name;
list.appendChild(item);
});
}
};
req.send();
}
function addPerson() {
var req = new XMLHttpRequest();
req.open("POST", '/join_class');
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) { listPerson(); } //Get list of Person on completion
};
var sName = document.getElementById("name").value;
req.send(JSON.stringify({ "name": sName }));
}
//Initially load a list of Person's
listPerson();

store images in postgresql from react using express multer

I'm trying to save images from my react app to backend using nodejs(express) and multer, I tried from these How to upload image using javascript fetch api and express multer
after I got the message file uploaded, how do you store it to database?
Here's the code in my react app
class UploadCover extends React.Component {
constructor(props){
super(props);
this.state={
id: this.props.location.state.id,
selectedFile : '',
imagePreviewUrl: ''
}
}
//handle image change
handleImageChange = (e) => {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () =>{
this.setState({
selectedFile:file,
imagePreviewUrl: reader.result
});
};
reader.readAsDataURL(file);
this.handleUploadCover(e.target.files[0]);
}
//upload cover
handleUploadCover = (file) => {
let form = new FormData(this.refs.myForm);
form.append('myImage', file);
fetch('http://localhost:3001/upload-cover', {
method: 'post',
header: { "Content-Type" : "application/json"},
body: form
})
.then( res =>res.json())
.then(data => console.log("data: ", data))
};
render() {
const { classes, ...rest } = this.props;
const { id, imagePreviewUrl } = this.state;
console.log("url: ", imagePreviewUrl)
let $imagePreview = null;
if(imagePreviewUrl){
$imagePreview = <img style={{width: "100%", height: "100%"}} src={imagePreviewUrl}/>;
}else{
$imagePreview = (
<div className={classes.previewText}>Please select cover</div>
);
}
return (
<div>
<HeaderHome/>
<div className={classNames(classes.main, classes.mainRaised)}>
<div className={classes.container}>
<div className={classes.storymargin}>
<h2 className={classes.title}>Upload Cover Story</h2>
<Card className={classes.uploadcontainer}>
<CardContent>
<div className={classes.imgPreview}>{$imagePreview}</div>
<form ref='myForm' encType='multipart/form-data'>
<input
accept="image/*"
className={classes.input}
id="raised-button-file"
multiple
type="file"
onChange={ e => this.handleImageChange(e)}
// ref='myForm'
/>
</form>
<label htmlFor="raised-button-file">
<Button component="span" className={classes.buttonupload}>
Choose Image
</Button>
</label>
</CardContent>
<CardActions>
<Link
to={{
pathname: "/create-chapter",
state: {id : id}
}}
>
<Button size="small" clor="primary" className={classes.buttonnextup}
onClick={ e => this.handleUploadCover(e) }
>
Next
</Button>
</Link>
</CardActions>
</Card>
</div>
</div>
</div>
<div className={classes.footer}>
<Footer />
</div>
</div>
);
}
}
and here's the backend
//set storage engine
const storage = multer.diskStorage({
destination: './public/uploads',
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
}
})
//Init upload
const upload = multer({
storage: storage,
limits: {fileSize: 1000000},
fileFilter: (req, file, cb) => {
checkFileType(file, cb);
}
}).single('myImage');
//Check File Type
checkFileType = (file, cb) => {
//Allowed ext
const filetypes = /jpeg|jpg|png|gif/;
//Check ext
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
//Check mime
const mimetype = filetypes.test(file.mimetype);
if(mimetype && extname){
return cb(null, true);
}else{
cb('Error: Images Only');
}
}
//upload cover story
app.post('/upload-cover', (req, res) => {
console.log('handling upload image');
upload( req, res, (err) => {
if(err){
console.log('first err', err);
res.send({
msg: err
});
}else{
if(req.file === undefined){
console.log('Error: No File Selected');
res.send({
msg: 'Error: No File Selected'
});
}else{
console.log('File Uploaded');
res.send({
msg: 'File Uploaded',
file: `uploads/${req.file.filename}`
});
}
}
});
});
and how can i send request with content type application/json and multipart/form-data at the same time through body request, I want to send form and id:this.state.id

Express Multer req.files is undefined

Whenever I upload an image, req.files returns undefined.
This is my code:
var upload123 = multer({
dest: path.join(__dirname, 'public/upload/temp'),
});
app.post(upload123);
This is the HTML:
<form action="/images" method="POST" enctype="multipart/form-data">
<div class="panel-body form-horizontal">
<div class="form-group col-md-12">
<label for="file" class="col-md-2 control-label">Browse:</label>
<div class="col-md-10">
<input type="file" class="form-control" id="file" name="file">
</div>
</div>
This is the controller I am trying to access req.files in:
create(req, res) {
const saveImage = function() {
const possible = 'abcdefghijklmnopqrstuvwxyz0123456789';
let imgUrl = '';
for(let i = 0; i < 6; i++) {
imgUrl += possible.charAt(Math.floor(Math.random() * possible.length));
}
Models.Image.find({ filename: imgUrl }, (err, images) => {
if (images.length > 0) saveImage();
else {
var tempPath = req.files.file.path,
ext = path.extname(req.files.file.name).toLowerCase(),
targetPath = path.resolve(`./public/upload/${ imgUrl }${ ext }`);
if (ext === '.png' || ext === '.jpg' || ext === '.jpeg' || ext === '.gif') {
fs.rename(tempPath, targetPath, (err) => {
if (err) throw err;
var newImg = new Models.Image({
title: req.body.title,
description: req.body.description,
filename: imgUrl + ext
});
newImg.save((err, image) => {
res.redirect(`/images/${image.uniqueId}`);
});
});
} else {
fs.unlink(tempPath, () => {
if (err) throw err;
res.json(500, {error: 'Only image files are allowed'});
})
}
}
});
}
saveImage();
}
I am using Express version 4.16.3 and Multer 1.3.0.
I check the docs but couldn't figure out how to simply provide a dest option in Multer. Please help, am new to Nodejs
This is example from code that is working properly:
const multer = require('multer');
const storage = multer.memoryStorage();
const fileUpload = multer({storage});
app.use('/*', fileUpload.single('file'));
If you have this in beginning of your application and you put controllers after this middleware, then in req.file you will have file
The best thing is that it is stored directly in memory, not in some file, so you dont have to load it from filesystem. (which is also safer, especially when you deploy your app to some cloud services and containers, which makes it less visible)
If you insist on your "file-on-disk" solution, based on official docs: https://www.npmjs.com/package/multer you should use it as this:
var upload123 = multer({
dest: path.join(__dirname, 'public/upload/temp'),
});
app.post('/endpoint/to/upload/photos', upload123.single('file'), controller.handleImage);

Resources