I am a js-newbie and I am currently trying to use multer to upload some files.
Here is my code:
let express = require('express');
let im = require('imagemagick');
let gm = require("gm").subClass({
imageMagick: true
});
let multer = require('multer');
let app = express();
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});
var upload = multer({storage: storage}).single('avatar');
app.post('/', function (req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
res.json({
success: false,
message: 'error during uploading'
});
} else if (err) {
res.json({
success: false,
message: 'error during uploading'
});
}
res.json({
success: true,
message: 'Image uploaded'
});
})
})
app.listen(3000);
When I send a post-req with a file (form-data), then I get a success message, however the folder with the file is not created:
post request
EDIT:
I managed to upload the file... I had to change the path of the uploads directory in the code like this:
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
However the uploads directory hast to be created manually, it is not being created automatically if it is missing...how do I solve this problem?
You can check this issue out:
https://github.com/expressjs/multer/issues/287
It says you should create a directory in 'destination' or as pre-requirements.
Related
i'm trying to upload files through postmon using multer ( nodejs ) but it show error. i don't know what happened in this code. i first time used multer module.
i need to upload multiple fields data like,
<input type="file1" >
<input type="file2">
so, what i do?
GSTPropritor.js
const multer = require('multer')
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./uploads");
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now());
},
});
const upload = multer({ storage: storage });
var uploadMultiple = upload.fields([
{ name: 'panCard' },
{ name: 'aadharCard' }
]);
const uploadDoc = async (req, res, next) => {
console.log(req.file)
}
module.exports = { uploadMultiple, uploadDoc };
console Error
Error: ENOENT: no such file or directory, open 'G:\legalapp-backend\uploads\panCard-1647792449153'rd-1647792449153'
routes.js
i pass the function and middleware like this...
router.post('/upload', uploadMultiple, uploadDoc);
I am trying to upload different types of files to server using multer in an express application. But every time server responds by stating TypeError: req.files is not iterable . I checked and req.files is empty.
Here is the code for the same:
var express = require('express');
var app = express();
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname)
}
})
var upload = multer({ storage: storage }).array('userfiles', 10);
app.post('/upload', function (req, res) {
upload(req, res, function (err) {
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
return res.status(500).json(err);
} else if (err) {
// An unknown error occurred when uploading.
return res.status(500).json(err);
}
let uploadedFiles = [];
for (let item of req.files) {
uploadedFiles.push({ filename: item.originalname });
}
// Everything went fine.
res.json({ progress: 100, files: uploadedFiles });
})
});
app.listen(8000, (err) => {
if (err) {
console.log('ERROR:', err);
} else {
console.log('working on http://localhost:8000');
}
})
And this is how I am calling this API from postman:
Postman UI
I am unable to figure out where the problem is. Please help me with this.
I ran his code and he tried to store the images at the root of my filesystem.
to refer a a path relative to your current directory you need to use ./
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/') // change 'upload/' to './uṕload'
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname)
}
})
After this, the code worked.
I am making API for multiple image uploading in node js.
So can you please help me out, how to upload only images and not another file
var Express = require('express');
var multer = require('multer');
var bodyParser = require('body-parser');
var app = Express();
app.use(bodyParser.json());
var Storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, "./Images");
},
filename: function (req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
});
var upload = multer({ storage: Storage }).array("imgUploader", 3); //Field name and max count
app.get("/", function (req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/api/Upload", function (req, res) {
upload(req, res, function (err) {
if (err) {
return res.end("Something went wrong!");
}
return res.end("File uploaded sucessfully!.");
});
});
You can add a fileFilter function to your multer options. So with a bit of refactoring:
var options = {
storage: multer.diskStorage({
destination: function (req, file, callback) {
callback(null, "./Images");
},
filename: function (req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
}
}),
fileFilter: function (req, file, callback) {
const isPhoto = file.mimetype.indexOf("image/") === 0
if (isPhoto) {
callback(null, true) // true if valid
} else {
callback({ message: 'An optional error message'}, false) // false if invalid
}
}
}
And then use these options:
var upload = multer(options).array("imgUploader", 3);
See: https://github.com/expressjs/multer#filefilter
accept="image/*" on your input will only provide client side validation, and can be removed with the dev console.
Use accept attribute for your input.
<input type="file" name="pic" accept="image/*">
I want to upload images using multer. But it is not working. What is wrong here?
This code is in my route file.
var multer = require('multer');
var upload = multer({ dest: 'public/uploads/' });
And this is my post route.
router.post('/addNewFood', upload.single('avatar'),function (req, res, next) {
console.log(req.files);
});
Try this, it works for me. Used express and node.
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/uploads/')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
});
var upload = multer({ storage: storage }).single('avatar');
router.post('/addNewFood', //Your authentication check,//
function (req, res, next) {
upload(req, res, function(err) {
if (err) {
res.redirect(req.headers.referer + "/error.html");
return;
}
if (!req.files) {
res.redirect(req.headers.referer + "/error.html");
return;
} else {
//Implement your own logic if needed. Like moving the file, renaming the file, etc.
res.redirect(req.headers.referer);
}
});
}
);
Make sure you install the package
npm install --save multer
You can try the following way,
In the server side, In your routes or controller file configure the multer:
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/images/uploads')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname)
}
})
var upload = multer({ storage: storage });
In the storage object,
destination is stand for, where the file will be uploaded. So make sure in your project directory, /public/images/uploads path is created. Otherwise you may want to change the file path.
Also in storage object filename is stands for, what will be the uploaded file name. Here I add the current time with the original file name to make the all file name unique.
Now in your desired routing, suppose
router.post('/', upload.single('image'), (req, res) => {
//here your other task.
});
Now your file is uploaded. Make sure the client side is using the same name, In this case 'image'.
<input type="file" name="image" id="image" class='form-control'>
This is a single file upload procedure.
For multiple files
router.post('/', upload.array(), function (req, res, next) {
//your task goes here
});
For more information, check this link.
const multer = require("multer");
function fileFilter(req, file, cb) {
if (file.mimetype === "image/jpeg" || file.mimetype === "image/jpg" || file.mimetype === "image/png") {
cb(null, true)
} else {
cb(null, false)
}
cb(new Error('I don\'t have a clue!'))
}
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9)
cb(null, file.fieldname + '-' + uniqueSuffix)
}
})
var upload = multer({
storage: storage, limits: {
fieldSize: 1024 * 1024 * 5,
fileFilter: fileFilter
}
})
router.post("/", upload.single("image_url"),(req, res) => {
const new User=new User({
image_url: req.file.path
})
routes.js
module.exports=function(app, upload){
var postingsController=require('../controllers/postings.server.controller');
app.post('/postings', postingsController.savePosting);
}
controller.js
var multer=require('multer');
exports.savePosting=function(req, res, next){
// this diskstorage function is not at all executed
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
console.log(file);
cb(null, file.filename + '.' + 'jpg');
}
});
var upload = multer({ storage: storage });
upload.single('attachment');
res.json({ message: "success" });
}
can someone tell me which line exactly uploads file. DO i write multer diskstorage configuration in main express configuration file or can i write any where. By the way i able to see json response which is from the line
Typically the middleware is created and inserted outside of any actual route handlers. For example:
routes.js
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads')
},
filename: function (req, file, cb) {
console.log(file);
cb(null, file.filename + '.' + 'jpg');
}
});
var upload = multer({ storage: storage });
module.exports = function(app, upload) {
var postingsController = require('../controllers/postings.server.controller');
app.post('/postings',
upload.single('attachment'),
postingsController.savePosting);
};
controller.js
exports.savePosting = function(req, res, next) {
// Use `req.file` to access attachment
if (req.file)
res.json({ message: "success" });
else // no file uploaded
res.json({ message: "failure" });
};
Multer is a middleware, which means it is added as a parameter to your route in most cases. So what the actual syntax would be like is:
app.post ("/postings", multer ({ ... }), postingsController.savePosting);
Multer gets called inbetween the request to "/postings" and the final function to do all the file work for you. It will then provide you with all the information via
req.files["fileInputName"]
in the following middlewares (your function is a "middleware", too).