multer node js upload image - node.js

when i send a new image the link apper like this:
uploads\854645135.jpg
i want to change this antislash"" to slash"/"
cause i can't find this data in frontend
const uploadRouter = express.Router();
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, 'uploads/');
},
filename(req, file, cb) {
cb(null, `${Date.now()}.jpg`);
},
});
const upload = multer({ storage });
uploadRouter.post('/',isAuth, upload.single('image'), (req, res) => {
res.send(`/${req.file.path}`);
});

Related

uploads folder as static using express not working

NOTE: I have tried and seen other similar issues but none resolved my problem thus posting again, thanks.
Hey everyone! I am trying to access the images uploaded in a folder at the backend/uploads directory which is marked as static but its not working as expected.
uplaodRoutes.js
const path = require("path");
const express = require("express");
const multer = require("multer");
const router = express.Router();
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, "backend/uploads/");
},
filename(req, file, cb) {
cb(
null,
`${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
);
},
});
function checkFileType(file, cb) {
const filetypes = /jpg|jpeg|png/;
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if (extname && mimetype) {
return cb(null, true);
} else {
cb("Images only!");
}
}
const upload = multer({
storage,
fileFilter: function (req, file, cb) {
checkFileType(file, CB);
},
});
router.post("/", upload.single("image"), (req, res) => {
req.file.size = req.file.size / 1000;
res.send(req.file);
});
module.exports = router;
server.js
app.use(
"/uploads",
express.static(path.join(path.resolve(), "backend/uploads"))
);
as we can see we cannot access it in browser.
const upload = multer({
**storage: fileStorageEngine,** add fileStorageEngine Parameter
storage: fileStorageEngine,
fileFilter: function (req, file, cb) {
**change from CB to cb**
checkFileType(file, cb);
},
});

Multer Doesn't Save Images in Local Folder

Multer cannot store the file, where the destination is in public/my-uploads
const express = require('express');
const app = express();
const multer = require('multer');
let storage = multer.diskStorage({
destination: '/public/my-uploads',
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});
const upload = multer({dest:'storage/'}).single('file');
app.post('/upload', upload, (req , res) => {
console.log(req.files) // this does log the uploaded image data.
})
Try this File Storage For Save image in Local
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images");
},
filename: (req, file, cb) => {
cb(
null,
new Date().toISOString().replace(/:/g, "-") + "-" + file.originalname
);
},
});
This happens because you are using windowsOS and where you learned it may be using macOS in windows Path have to setted as mentioned in the above code.
You simply set the file name as given in my answer and destination is root dir "./images"...

NodeJS multer filename for fields

I'm nodeJS beginner. How to get filenames for multer storage fields?
controller:
exports.createTruckDocs = (req, res, next) => {
console.log("tu");
Truck.findOneAndUpdate({ _id: req.body.truckId}, {$set: {TLic: /*issue*/}}).then(createdDocs => {
res.status(201).json(createdDocs);
})
};
middleware:
module.exports = multer({ storage: storage }).fields([
{ name: "TLIC"},
{ name: "LIC" },
{ name: "CMRLIC" }
]);
Thanks in advance!
So, this is how you should save the file with multer. I am not sure which steps is confusing, but this is how you should do:
const multer = require("multer");
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, './uploads'); // you can name the destination make sure it exists
},
filename: function (req, file, cb) {
cb(null , file.originalname);
}
});
// to save single files
//const upload = multer({ storage: storage }).single('fieldName')
// to save multiple files, you can also set limit
const upload = multer({ storage: storage }).array('fieldName')
app.post("/upload_files", upload.array("fieldName"), uploadFiles);
const uploadFiles = (req, res) => {
console.log(req.body);
console.log(req.files);
res.json({ message: "Successfully uploaded files" });
}
You can check here for more details.

How to use Multer to upload a file in two different directories?

I'm new in using nodejs and multer and I want to upload an image but in two different directories. I tried using two different middleware but since the first multer function returns a file destination I couldnt use it to upload in the other multer function. Is it possbile to upload a file using multer in two different directories?
Create multiple storages and call them at the same time.
Example:
const app = require("express")();
const multer = require('multer');
const storageA = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './storageA/');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
const storageB = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './storageB/');
},
filename: function (req, file, cb) {
cb(null, file.originalname);
}
});
const destA = multer({ storage: storageA });
const destB = multer({ storage: storageB });
function fileUpload(req, res, next) {
destA.single('file')(req, res, next);
destB.single('file')(req, res, next);
}
app.post("/", fileUpload, (req, res) => {
res.json({ file: req.file });
});
app.listen(3000, () => {
console.log("Server started");
});
The uploaded file will be store in ./storageA and ./storageB.
This is not an official way, but went I try it, it works!

Multer upload an image to node js server (Github as storage)

I deployed a web based application but the multer upload doesn't work. It does work in localhost there is no error but the file/s are not save in my director. Here is my code:
const multer = require("multer");
const imageFilter = (req, file, cb) => {
if (file.mimetype.startsWith("image")) {
cb(null, true);
} else {
cb("Please upload only images.", false);
}
};
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __basedir + "/resources/static/assets/uploads/");
},
filename: (req, file, cb) => {
cb(null, `${file.originalname}`);
},
});
var uploadFile = multer({ storage: storage, fileFilter: imageFilter });
module.exports = uploadFile;
What happen is the __basedir expression will cause "Uncaught ReferenceError: __basedir is not defined" error, but it's silently eaten in the code. To get the error to properly propagate, try adding try-catch block around the offending line this:
const storage = multer.diskStorage({
destination: (req, file, cb) => {
try {
cb(null, __basedir + "/resources/static/assets/uploads/");
} catch (e) {
cb(e);
}
},
filename: (req, file, cb) => {
cb(null, `${file.originalname}`);
}
});

Resources