Answer the question
In order to leave comments, you need to log in
How to properly upload files to Node.js server?
Hello.
Tell me, for what reason the Node server can not load files?
When starting the server on a localhost, everything works fine, but if I copy the same code to a virtual server and run it there, I can’t upload files from the front form, I get an error 500. I
start the server the same way, without a proxy. Those. it works on its port, as well as when running on a localhost.
At the same time, I receive images uploaded via FTP from the server, and all requests where there are no files work fine.
I use multer to download.
Here is an example code:
const multer = require('multer');
const moment = require('moment');
const path = require('path');
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, 'files/uploads/');
},
filename(req, file, cb) {
const date = moment().format('DDMMYYYY-HHmmss_SSS');
const ext = path.extname(file.originalname);
const name = path.basename(file.originalname, ext);
cb(null, `${date}-${file.originalname.replace(/\s/g, '')}`);
},
});
const fileFilter = (req, file, cb) => {
if (file.mimetype === 'image/png' || file.mimetype === 'image/jpeg') {
cb(null, true);
} else {
cb(null, false);
}
};
const limits = {
fileSize: 1024 * 1024 * 5,
};
module.exports = multer({ storage, fileFilter, limits });
cb(null, '../files/uploads/');
Answer the question
In order to leave comments, you need to log in
To avoid path problems in different environments, always build paths using the __dirname variable or other paths derived from it.
To join several parts of a path into a full path, use path.join
Most libraries build relative paths from process.cwd() , which directly depends on which folder the script was run from.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question