Search code examples
node.jsmulter

get folder size before form submission


Hi there I've made a form which actually uploads songs to a server folder but am trying to find a way to put a limit on a folder prompting users that they reached the limit before submitting the form.

Server side

var storage = multer.diskStorage({
destination: function(req, file, callback) {
    callback(null, './uploads');
    },
filename: function(req, file, callback) {
    callback(null, file.originalname);
    }
});

var limits = {
    files: 100, 
    fileSize: 50000000
};

var upload = multer({
    storage: storage,
    fileFilter: function(req, file, callback) {
        var ext = path.extname(file.originalname);
        if (ext !== '.mp3' && ext !== '.wav' && ext !== '.m4a' && ext !== '.flac' && ext !== '.aac') {
            return callback(new Error('You are only allowed to upload audio files.'))
        }
        callback(null, true)
    },limits:limits
}).any('SongFile');

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

app.post('/api/photo', function(req, res) {
    upload(req, res, function(err) {
        if (err instanceof multer.MulterError) {
            return res.end("Some error occured.");
        }else if (err) {
            return res.end("You are only allowed to upload audio files.");
        }
        res.end("Songs are uploaded");
    });
});

index.html(form)

<form id="uploadForm" method="post" action="/api/photo" encType="multipart/form-data">
<input type="file" multiple='multiple' name="SongFile" ><br>
<input type="submit" value="Submit">
<span id = "status"></span>
</form>

Solution

  • After making app.post function to asynchronous and using get-folder-size module it works like a charm now.

    app.post('/api/photo',async (req, res)=> {
        try 
        {
            getSize('./uploads/', (err, size) => {
                if (err) { throw err;}
                else if(size>100000000){
                    return res.end("Daily upload limit reached!!Cannot upload for now")
                    }
                upload(req, res, function(err) {
                    if (err instanceof multer.MulterError) {
                        return res.end("Some error occured.");
                    }else if (err) {
                        return res.end("You are only allowed to upload audio files.");
                    }
                    res.end("Songs are uploaded");
                });
    /*          console.log('Uploads folder is ' + size / 1024 / 1024).toFixed(2) + ' MB');
     */         });
        }catch (error){
    
        }
    });