Multer storage is not uploading file on server directory - node.js

Multer is not uploading files on server directory below my source code to upload file. file object is created that means when i log req.files file are present but not uploading to directory.im using POSTMAN for API Testing sending file through formdata->uploadfiles and with key "uploadfiles" destinition function is not called because log inside function is not console the name "Hello "
const storage = multer.diskStorage({
destination: function (req, file, cb) {
console.log("Hello Umesh");
cb(null, '../resources/uploads'); // Absolute path. Folder must exist, will not be created for you.
},
filename: function (req, file, cb) {
console.log("Hello Umesh");
cb(null, file.fieldname + '-' + Date.now());
}
});
const upload = multer({
storage: storage,
limit:{filesize:10}
}).single('uploadfiles');
router.post('/save', function (req, res) {
upload(req, res, function (err) {
if (err) {
res.json({
success: false,
message:err
});
}
else{
res.json({
success: true,
message: req.file
});
}
})
});

Try to use the absolute path to the storage location:
cb(null, require('path').join(__dirname, '..', 'resources', 'uploads'));
instead:
cb(null, '../resources/uploads');
Update:
Since the working directory for functions from the fs module is the project's root folder (if you run the project with the npm start command), you can simply use this:
cb(null, 'resources/uploads');

Related

Multer - handle missing file

I'm using multer as express middleware to upload a file like so:
const upload = multer().single('fieldName');
router.post(
'/',
upload,
(req, res) => {
console.log(req.file)
}
);
It works fine except when I sent the form without a file. Then apparently the upload middleware is just skipped and req.file is undefined.
I tried to add a filter like so but apparently the filter function is not called when there is no file:
function fileFilter(req, file, cb) {
console.log('filtering'); //never reached when file is missing
if (!file) {
return cb(new Error('no file', false));
}
cb(null, true);
}
const upload = multer({fileFilter: fileFilter}).single('fieldName');
router.post(...)
Is there any way to handle the missing file inside the multer middleware? Or do I have to check afterwards?
check in you html form "fieldName" in input name
and this can you help
in you routes app
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now()+'.mp3')
}
})
var upload = multer({ storage: storage })
router.post(
'/uploadfile',upload.single('fieldName'),
)

Same Image not uploading in express

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!

Uploading image using api in node express using multer package

This question has been asked before. But as I have failed to get solution for my problem, I am asking again.
I am trying to upload image for a property using multer package as form-data so I can store other data and path of image in the database. I am using node express.
My api--
api.post('/service', upload.single('servicesImage'),
(req, res, next) => {
console.log(req.file);
Company.find({ domain: req.headers.domain },
(err, company) => {
const servicecontent = new Servicecontent({
description: req.body.description,
created_at: Date.now(),
created_by: req.body.user_id,
company_domain: req.headers.domain,
company_uuid: company[0].uuid,
image: req.file.path,
})
servicecontent.save(err => {
console.log(err);
});
res.json({ status: "success" });
});
});
I watched a tutorial, and from that I added these codes to upload image and other options--
const storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, './src/uploads/');
},
filename: function(req, file, cb){
cb(null, new Date().toISOString()+ file.originalname);
},
});
const upload = multer({storage: storage, limits:{
fileSize: 1024*1024*5
},
fileFilter: fileFilter
});
const fileFilter = (req, file, cb) =>{
if(file.mimetype=== 'image/jpeg' || file.mimetype=== 'image/png'){
cb(null,true);
}else{
cb(null,false);
}
};
Now when I send data and image through Postman , from console.log(req.file)
I get valid data as I saw from the tutorial. Api responds without any errror, and in database I can see all datas are stored including image path. But the issue I am facing is that in src/upload folder is empty, no image is uploaded.
N.B. -- I am using linux 18.04 Os, and fs package can't be installed. So src/upload folder wasn't creating when I were sending req, so I created this directory from folder.
Edit: I can upload image with this code now, I don't exactly know why this wasn't working earlier. I should close this question, if possible.
I can upload image with this code now, I don't exactly know why this wasn't working earlier. I should close this question, if possible.
Try this to store images.
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
console.log(file);
cb(null, makeid(3) + file.originalname)
}
})
var upload = multer({ storage: storage })
`

How to get the filename and file path of files already stored in a folder?

I have uploaded files of different types(image, pptx, video and docx) using Multer in the folder named 'uploads'.
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.originalname);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
/** API path that will upload the files */
app.post('/upload', function(req, res) {
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0,err_desc:null});
});
});
Now the uploaded files are being stored in 'uploads' folder like /uploads/demo.pptx
I need to fetch these and send the filepath or url of the stored files and send as a response to client so they can access to watch or download it.
Usually, files stored in DB when you need to do more than just serve them and upload new files. For this proposes, you could save only file's metadata to DB(such as size, type, path, name). However if you for some reason still need to store files in DB, MongoDB have GridFS component and provides a documentation about working with this component.
you can do something like this:-
var mongojs = require('mongojs');
var db = mongojs(//credential here);
var uploaded_file=db.collection("uploaded_file");
var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './uploads/');
},
filename: function (req, file, cb) {
var datetimestamp = Date.now();
cb(null, file.originalname);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
/** API path that will upload the files */
app.post('/upload', function(req, res) {
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}else{
uploaded_file.insert(res.file,function(err, saved) {// i am asuming res.file have the information you needed to send
if(err){
console.log("Unexpected error occurred during insertion in database:"+err);
}else{
res.send({error_code:0,file_info:res.file});
res.end();
}
});
}
});
});

multer save image without mimetype

I'm using "multer": "^1.0.6", And i Want to save image in upload folder.
My code is
app.post('/post', multer({dest: './uploads/'}).single('file'), function (req, res) {
response = {
message: 'File uploaded successfully',
filename: req.file.filename
};
res.end(JSON.stringify(response));
});
But I Have the file with this name in upload folder 8e6e425f8756e0bafb40ed1a3cb86964
Why I have this name without mimetype?
Multer saves files without extensions you can read this on GitHub:
filename is used to determine what the file should be named inside the folder. If no filename is given, each file will be given a random name that doesn't include any file extension.
If you want to save with the extension that you write your code like here:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/tmp/my-uploads')
},
filename: function (req, file, cb) {
cb(null, file.originalname); // modified here or user file.mimetype
}
})
var upload = multer({ storage: storage })
All information you can find here https://github.com/expressjs/multer/blob/master/README.md
Multer not worried about the extension of the file and leave it completely on your side: you have to define itself a function that will do it. For example, like this:
var multer = require('multer');
var upload = multer({ storage: multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './uploads');
},
filename: function (req, file, cb) {
var ext = require('path').extname(file.originalname);
ext = ext.length>1 ? ext : "." + require('mime').extension(file.mimetype);
require('crypto').pseudoRandomBytes(16, function (err, raw) {
cb(null, (err ? undefined : raw.toString('hex') ) + ext);
});
}
})});
app.post('/post', upload.single('file'), function (req, res) {
response = {
message: 'File uploaded successfully',
filename: req.file.filename
};
res.end(JSON.stringify(response));
});

Resources