skip to Main Content

I am trying to determine if a file that is uploaded is either a video or photo. I need this so that based on the file extension, I can send a video or photo to my telegram bot.

What is throwing me off, is that the logic I have seems to be right:

form.parse(req, (err, fields, files) => {
        if (err) {
            res.render('error')
        } else {
            console.log('File uploaded : ' + files.upload.path + '/' + files.upload.name);
            console.log('Fields : ' + fields);
            console.log(path.extname(files.upload.name))
            if(path.extname(files.upload.name).toLowerCase() === ".jpeg" || ".jpg" || ".png" || ".tiff" || ".gif") {
                console.log("image")
            }
            else if(path.extname(files.upload.name).toLowerCase() === ".mp4" || ".m4a"|| ".f4v" || ".m4b" || ".mov") {
                console.log("video")
            }
            else {
                render('error')
            }
            res.render('success')
        }
    });

When uploading an .mp4 video file, it prints that it is a .mp4, but then prints image. I’m unsure as to why this is happening. Any help is greatly appreciated.

2

Answers


  1. The or comparison your are attempting to use is not working as you think it is. Only your first comparison is using the value of path.extname(files.upload.name).toLowerCase(), the others are evaluting string’s truthiness and returning appropriately. As such that first if is always going to be entered.

    E.g.

    > x = 5
    5
    > if ( x == 4 || ".jpg" ) {console.log("Yep")};
    Yep
    > if ( x == 5 && "" ) {console.log("Yep")};
    undefined
    > if ( x == 5 && "yep" ) {console.log("Yep")};
    Yep
    
    Login or Signup to reply.
  2. There is problem with your code

    form.parse(req, (err, fields, files) => {
        if (err) {
            res.render('error')
        } else {
            console.log('File uploaded : ' + files.upload.path + '/' + files.upload.name);
            console.log('Fields : ' + fields);
            console.log(path.extname(files.upload.name))
            let extension = path.extname(files.upload.name).toLowerCase();
            if(extension  === ".jpeg" || extension === ".jpg" || extension === ".png" || extension === ".tiff" || extension === ".gif") {
                console.log("image")
            }
            else if(extension  === ".mp4" || extension === ".m4a"|| extension === ".f4v" || extension  === ".m4b" || extension  === ".mov") {
                console.log("video")
            }
            else {
                render('error')
            }
            res.render('success')
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search