I am using multer for uploading my images and documents but this time I want to restrict uploading if the size of the image is >2mb. How can I find the size of the file of the document? So far I tried as below but not working.
JavaScript
x
21
21
1
var storage = multer.diskStorage({
2
destination: function (req, file, callback) {
3
callback(null, common.upload.student);
4
},
5
filename: function (req, file, callback) {
6
console.log(file.size+'!!!!!!!!!!!!!!')======>'Undefined'
7
var ext = '';
8
var name = '';
9
if (file.originalname) {
10
var p = file.originalname.lastIndexOf('.');
11
ext = file.originalname.substring(p + 1);
12
var firstName = file.originalname.substring(0, p + 1);
13
name = Date.now() + '_' + firstName;
14
name += ext;
15
}
16
var filename = file.originalname;
17
uploadImage.push({ 'name': name });
18
callback(null, name);
19
}
20
});
21
Can anyone please help me?
Advertisement
Answer
To get a file’s size in megabytes:
JavaScript
1
6
1
var fs = require("fs"); // Load the filesystem module
2
var stats = fs.statSync("myfile.txt")
3
var fileSizeInBytes = stats.size;
4
// Convert the file size to megabytes (optional)
5
var fileSizeInMegabytes = fileSizeInBytes / (1024*1024);
6
or in bytes:
JavaScript
1
6
1
function getFilesizeInBytes(filename) {
2
var stats = fs.statSync(filename);
3
var fileSizeInBytes = stats.size;
4
return fileSizeInBytes;
5
}
6