получите размер папки перед отправкой формы

#node.js #multer

Вопрос:

Привет, я создал форму, которая фактически загружает песни в папку сервера, но пытаюсь найти способ ограничить доступ к папке, запрашивая у пользователей, что они достигли предела, прежде чем отправлять форму.

На стороне сервера

 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' amp;amp; ext !== '.wav' amp;amp; ext !== '.m4a' amp;amp; ext !== '.flac' amp;amp; 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 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>
 

Ответ №1:

После преобразования функции app.post в асинхронную и использования модуля get-folder-size теперь она работает как заклинание.

 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){

    }
});