Having trouble implementing filefilter for redirecting to another page in Express.js

var express = require('express');
var router = express.Router();
var multer = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'public/uploads/');
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});
var upload = multer({
    storage: storage, fileFilter: function (req, file, cb) {
        if (file.mimetype !== 'image/png' && file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg') {
            return cb(null, false);
        }
        return cb(null, true);
    }
}).any();



/* get home page. */
router.get('/', function (req, res) {
    res.render('index', { title: 'express' });
});

router.post('/', function (req, res) {
    upload(req, res, function (err) {
        if (err) {
            //I want to jump to another page
        } else {
            res.send(req.files);
        }
    });    
});

module.exports = router;

In the event of an error (if (err)), I am trying to redirect to a specific page in my views folder named "wrong". However, simple redirection methods like res.redirect('wrong') or res.redirect('views/wrong') are not working for me. I have tried numerous approaches without success. If I upload a file that is not an image, it redirects to a page displaying only an empty array '[]'. How can I achieve successful redirection in this scenario?

Answer №1

Here is one way you could handle this situation:

router.post('/', function (req, res) {
    upload(req, res, function (err) {
        if (err) {
            res.redirect('/?error=upload_error');
        } else {
            res.send(req.files);
        }
    });    
});

Make sure to utilize the upload_error identifier in your page to display any errors.

Answer №2

When dealing with file uploads, it's important to handle different scenarios properly. For instance, if a user tries to upload the wrong type of file, they should be notified accordingly.

var express = require('express');
var router = express.Router();
var multer = require('multer');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'public/uploads/');
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});
var upload = multer({
    storage: storage, fileFilter: function (req, file, cb) {
        if (file.mimetype !== 'image/png' && file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg') {
            req.fileValidationError = 'File type is not supported';
            return cb(null, false, new Error('File type is not supported'));
        }
        return cb(null, true);
    }
}).any();

/* Get the home page */
router.get('/', function (req, res) {
    res.render('index', { title: 'express' });
});

router.post('/', function (req, res) {
    upload(req, res, function (err) {
        if (req.fileValidationError) {
            // Redirect to another page
            res.send("You didn't upload a valid image");
        } else {
            res.send(req.files);
        }
    });    
});

module.exports = router;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Express (NodeJS) is failing to execute response.redirect()

I am trying to redirect from login.html to dashboard.html if the username is correct. If not, I want an alert box to be displayed. I have attempted to use both express response.redirect('path') and response.sendFile('path'), but neither ...

Create an HTML table with a line separating two table cells

I need help with creating a table row and td's dynamically using basic HTML and CSS. I would like to draw lines between the td's similar to the example image shown below. Can someone please assist me in achieving this? https://i.sstatic.net/GPd ...

Issue with AngularJS form not binding to $http request

<form novalidate class="form-horizontal"> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="text-capitalize"> </ ...

Looping through multi-dimensional JSON objects with jQuery

Hello there, I'm currently facing some challenges in getting the screen below to work properly: Project progress screen I have generated the following JSON data from PHP and MYSQL. My goal is to display the project alongside user images and names whe ...

Organizing files in an ExpressJs project with Angular2

What is the conventional file structure for a mix of ExpressJs and Angular2 projects? Here's my current setup: Project | |--bin |--node_modules |--public |--images |--javascripts |--stylesheets |--routes |--views |--app.js |-- ...

Maintain the original order of rows in the table while shuffling the columns they appear in randomly

I need help with my table setup. The left column contains words in English, while the right column has the same words translated into Korean. Is there a way to keep the rows intact while randomizing the order of the columns? Here's an example: <ta ...

difficulty in obtaining information submitted through a form

I'm having an issue with my contact form. I tried testing to see if I can retrieve the values from the form, but it's giving me back: name: undefined I'm not sure why it's not working! Here is the code for the form: <form met ...

What is the correct way to change the v-model value of a child component within a parent component

Currently, I am in the process of mastering Vue.js and I have a specific goal. I want to modify the binding value of the child component's v-model and then trigger an event in the parent component. As I delve into the Element UI documentation, I aim ...

The responsiveness of Angular Material appears to be limited when tested in Chrome's debug mode for different devices

I have come across a peculiar issue. Within my HTML file, I have defined two attributes: Hide me on small devices Hide me on larger than small devices When I resize the window, the attributes work as intended. However, when I enter device debug mode ( ...

ExpressJs does not support query parameters with the router.get method

I am currently working on developing an Express app. Here is the code snippet I am using: const express = require("express"); const router = express.Router(); router.get("/:id", ControllerHandler(UserController.getSingle, GetUserReque ...

Exploring a utility function for saving object information in a dynamic state

Imagine my state was structured like this: state = { customer: { name: { elementType: "input", elementConfig: { type: "text", placeholder: "Your Name" }, value: "" }, street: { e ...

What is the best way to set up multiple unique uglify tasks in grunt?

I am facing issues when trying to create multiple Uglify tasks in Grunt. Currently, I have to toggle between commenting and uncommenting a task to get it to work properly. I need assistance in generating two separate minified .js files using this plugin ...

Unable to retrieve PHP data using AJAX

Index.html → <form> <div class="form-group"> <!-- <input type="text" id="name" class="form-control" placeholder="Enter Name"> --> </div> <div ...

Seeking help with executing JQuery Ajax functions within a foreach loop

Currently, I am engrossed in the study of programming and endeavoring to construct a website utilizing .Net Core. The predicament at hand pertains to my limited acquaintance with JavaScript while incorporating two JQuery/AJAX functions on my Index page - o ...

The components declared in the index file are rendered on every route throughout the React application

I'm a beginner with React and I'm using react-router version 6.0.2. My issue is that I created a component for the router and then called this component in the index file. However, when I add another component to the index file, it gets rendered ...

Node.js Express - Setting the route for the main folder of the application

When working on my app, I encountered an issue while trying to access a folder containing .js controller modules. In one of my .html files, I have the following script declared in the head section: The problem arises when the application is running, as i ...

Mismatch in SSL version or cipher for ExpressJS

I am encountering an issue with https in express and I am struggling to comprehend it: Here is the code snippet from my previous project (which functions correctly): index.js: var fs = require('fs'); var http = require('http'); var ...

Identifying IPV6 Private and Loopback Addresses in Node.js: A Guide

Right now, I am looking for a way to distinguish between private addresses and web reachable ones. I am seeking a method to test for the following: Given a list of ipv6 addresses on an interface, I need to identify which ones are web reachable. It's ...

Refresh KendoUI Grid data with latest additions

I currently possess: $.post('buying-grid/split/' + config.route.params.id, item).success(function(data){ var ds = new kendo.data.DataSource(); ds.data(data) $('#buyingGrid').data('ke ...

Having trouble with loading a new page on an HTML website

My website is successfully updating the database, printing all values, but for some reason the new page is not opening. The current page just keeps refreshing and I'm receiving a status of 0. Below is my code snippet: try{ console.log("here1 "+e ...