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.
Related
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}`);
});
i have a user.js in model folder
const UserSchema = new mongoose.Schema({
name: {
type: String,
},
profile_pic: {
data: Buffer,
contentType: String
}
})
i want to upload a profile picture
and in the router folder i defined the storage using multer
const storage = multer.diskStorage({
destination: (req, file, callback) => {
callback(null, './images')
},
filename: (req, file, callback) => {
callback(null , Date.now()+ file.originalname)
}
})
const upload = multer({
storage : storage,
limits : {
fieldSize : 1024*1024*3
}
})
router.post('/image' , upload.single('image'),image)
using postman i tried to upload an image .. it uploaded successfully and stored in the defined folder (images)
but i want to store the image in the model too
how to store it in the controller folder user.js
Try the example below
const app = require("express")();
const multer = require('multer')
const firstLocation = multer.diskStorage({
destination: function (req, file, cb) {');
cb(null, './imagesFolder/')
},
filename: (req, file, callback) => {
callback(null , Date.now()+ file.originalname)
}
});
const secondLocation = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './modelFolder/')
},
filename: (req, file, callback) => {
callback(null , Date.now()+ file.originalname)
}
});
const firstPath = multer({ storage: firstLocation })
const secondPath = multer({ storage: secondLocation })
function fileUpload(req, res, next) {
firstPath.single('file')(req, res, next);
secondPath.single('file')(req, res, next);
next();
}
app.post("/", fileUpload, (req, res) => {
res.send("Received file");
});
app.listen(3000, () => {
console.log("Server started");
});
If you run the above code and send a request to localhost:3000 then you will notice that two directories created named imagesFolder and modelFolder. Inside those folders, you will see the file that you have uploaded.
Updated answer in response to comments for Mongo schema,
const imagePath = '/path/to/myImage.jpg';
const imageUp = mongoose.model('imageUp', UserSchema);
mongoose.connection.on('open', function () {
imageUp.remove((err) => {
if (err) throw err;
const up = new imageUp;
up.img.data = fs.readFileSync(imagePath); // read from you folder
up.img.contentType = 'image/jpg'; // set the content tpe to image format
up.save((err, a) => { // save or upload image
if (err) throw err; // throws error if anything goes wrong
app.get('/', (req, res, next) => {
imageUp.findById(up, (err, doc) => { // fetch image from db by id and send in response as required.
if (err) return next(err);
res.contentType(doc.img.contentType);
res.send(doc.img.data);
});
});
}
Ref:- https://www.geeksforgeeks.org/upload-and-retrieve-image-on-mongodb-using-mongoose/
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!
I am trying to upload an image using express but I am facing two problems, first, whenever I upload the same image again it's not getting uploaded and secondly after uploading any single image a file with image also uploading. Here is my code.
var multer = require('multer');
var uploads = multer({dest: './images'});
app.post('/uploading', uploads.single("file"), function (req, res) {
var file = __dirname +"/images" + "/" + req.file.originalname;
fs.readFile( req.file.path, function (err, data) {
fs.writeFile(file, data, function (err,data) {
if( err ){
console.error( err );
response = {
message: 'Sorry, file couldn\'t be uploaded.',
filename: req.file.originalname
};
}else{
response = {
message: 'File uploaded successfully',
filename: req.file.originalname
};
}
res.end( JSON.stringify( response ) );
});
});
})
The uploads.single("file") middleware Will handle the file upload. You don't have to specifically fs.read and fs.write the file.
var multer = require('multer');
var uploads = multer({dest: './images'});
app.post('/uploading', uploads.single("file"), function (req, res) {
//the file is uploaded automatically
})
EDIT: The above code will upload the file with hex string as filename without any extension.
In order to add rename function you need to use diskStorage. Here is the code taken from this github issue page.
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './images/')
},
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype)); //this is the rename func
});
}
});
var uploads = multer({ storage: storage });
app.post('/uploading', uploads.single("file"), function (req, res) {
//the file is uploaded automatically
})
Now you can use the uploads variable as middleware as shown in the above snippet.
you can edit the filename: function (req, file, cb) { .. } according to your needs. Now the filename will be, <16characterhexstring>.ext
another way to handle it will be not using middleware and using multer manually with below options :
try {
var storage = multer.diskStorage({
destination: function(request, file, callback) {
//define folder here by fs.mkdirSync(anyDirName);
},
filename: function(req, file, callback) {
callback(null, anyFileName);
},
limits: self.limits
});
var upload = multer({
storage: storage,
fileFilter: function(request, file, callback) {
// here you can filter out what not to upload..
}
}).any();
upload(request, response, callback);
} catch (e) {
}
hope this helps!
I'm working on a Node.js/MongoDB based website and i'm trying to upload images directly on server using Express, Jade, and Multer, but no matter what i do, i can't achive to upload the file with extension.
I've got this on my app.js file:
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
var upload = multer({ storage: storage });
var app = express();
mongoose.connect("mongodb://localhost/primera_pagina");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(multer({dest: "./uploads"}).single("image_avatar"));
var productSchema = {
title:String,
description:String,
imageURL:String,
pricing:Number
};
var Product = mongoose.model("Product", productSchema);
app.set("view engine","jade");
app.use(express.static("public"));
app.get("/",function(req,res){
res.render("index");
});
app.post("/productos",function(req,res){
if(req.body.password == "123"){
var data = {
title: req.body.title,
description: req.body.description,
imageURL: "image_avatar",
pricing: req.body.pricing
}
var product = new Product(data);
console.log(req.file)
}else{
res.render("index");
}
});
app.get("/productos/new",function(req,res){
res.render("productos/new");
});
app.listen(8080);
Any idea? I've search on Internet and tried every single method to add file extension with multer, but none has worked.
Multer strips the file extension for both security and collision reasons. For a workaround, try this:
var path = require('path')
var multer = require('multer')
var mime = require('mime-types')
var storage = multer.diskStorage({
destination: './uploads/',
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
if (err) return cb(err)
cb(null, raw.toString('hex') + mime.extension(file.mimetype))
})
}
})
var upload = multer({ storage: storage })
(from https://github.com/expressjs/multer/issues/170#issuecomment-123402678)
It assigns a random file name, but keeps the file extension in tact.
You should also be using the authorize field in multer, since it looks like you only want files when the user has the correct password. Do something like this:
var upload = multer({ storage: storage }, limits : { fileFilter: authorize });
function authorize(req, file, cb) {
if (req.body.password == PASS) {
cb(null, true); //accept
} else {
cb(null, false); //reject
}
}
This will only save the file to disk if the user has inputted the correct password.
You can pass the right parameters for Multer like this in order to save the file extension:
var multer = require('multer');
var path = require('path')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname))
}
})
var upload = multer({ storage: storage });