I am using multer with express, when I upload the file multer's storage engine returns a path that also includes the public folder which is used by express static as I am using ejs template. Is there any way so that the returned path don't include the public folder name in it?
// Node App Configs
const app = express();
app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/profile', express.static('uploads'));
// Storage Engine
const storage = multer.diskStorage({
destination: './public/upload',
filename: (req, file, cb) => {
return cb(null, `${file.fieldname}_${Date.now()}${path.extname(file.originalname)}`)
}
})
const upload = multer({
storage: storage,
limits:{
fileSize: 10485760
}
})
function errHandler(err, req, res, next) {
if (err instanceof multer.MulterError) {
res.json({
success: 0,
message: err.message
})
}
}
app.use(errHandler);
// Path that is being returned by multer
public\upload\profile_1609198415143.PNG
Is there any way so that this path that is returned don't include "public\ " in it?
From the doc File information, we know req.file.path
is the full path to the uploaded file. It generated by path.join(destination, filename)
statement, see disk.js#L37.
You can remove the public/
string like this:
console.log(req.file);
const path = req.file.path.split('/').slice(1).join('/');
console.log(path);
Output:
{ fieldname: 'file',
originalname:
'Stack Exchange personalized prediction data 2020-12-21.json',
encoding: '7bit',
mimetype: 'application/json',
destination: './public/upload',
filename: 'file_1609299871948.json',
path: 'public/upload/file_1609299871948.json',
size: 99765 }
upload/file_1609299871948.json