Is there a way to upload a file using express/multer without triggering a redirect?

Note: Despite coming across this post, I couldn't find it helpful. Other related posts were focused on angular/react, which are not relevant to my current project.

I have implemented a file upload feature that should provide a response indicating whether the uploaded file is of the correct type. While the file upload functionality works as intended, the issue arises when the page automatically redirects to the file's location. My goal is to keep the page on the same location after the file is uploaded.

home.ejs:

<!-- upload video -->
<form method="post" action="/upload" class="custom-file" enctype="multipart/form-data">
  <input type="file" name="video-file" class="custom-file-input" />
  <span class="custom-file-control"></span>

  <div class="dropdown">
    <button class="btn btn-secondary dropdown-toggle" 
            type="button" 
            id="dropdownMenuButton" 
            data-toggle="dropdown" 
            aria-haspopup="true" 
            aria-expanded="false"
            name="number-of-cores">
      Use all Cores
    </button>
    <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
      <a class="dropdown-item">Use all Cores</a>
      <a class="dropdown-item">Use one Core</a>
    </div>
  </div>

  <input class="btn btn-primary upload-btn" type="submit" id="upload-btn" value="Upload">

The reason for avoiding page redirection is to display whether the uploaded file format is correct or not directly on the same page without any interference.

$('body').on('click', '#upload-btn', function (event) {
      $.ajax({
          type: 'POST',
          url: '/',
          dataType : "application/json; charset=utf-8",
          contentType: JSON.stringify(false),
          success: function (response) { 
              $("#errorMessage").html("* file successfully opened");
              console.log('successfully uploaded', response);
          },
          error: function (result) {
              $("#errorMessage").html("* Incorrect file/no file given");
              console.log('couldn\'t upload');
          }
      });
      //return false;
  })

server.js

const express = require('express');
const multer = require('multer');
var path = require('path')

const app = express();

app.set('view engine', 'ejs');
app.set('views', './views');
app.use(express.static('public'));

function fileFilter (req, file, cb) {
    if (path.extname(file.originalname) !== '.mp4') {
        return cb(null, false);
    }

    cb(null, true);
}

const upload = multer({ dest: 'uploads/', fileFilter:fileFilter});

app.get('/', (req, res) => {
    res.render('home', { testGreeting: 'Hello world' });
});

app.post('/upload', upload.single('video-file'), function(req, res) {
    console.log(req.file);
    console.log(req.params);
    if (req.file) {
        console.log("successfully received");
        res.send({success: "success"});
    }
    return res.end();
});

app.listen(3000, () => console.log('Listening on Port 3000.'));

On a side note, my ajax code consistently triggers the error block and never the success block. Any assistance with this would be highly appreciated. Thanks!

UPDATE: event.preventDefault() was the solution:

$('body').on('click', '#upload-btn', function (event) {
      event.preventDefault();
      $.ajax({
              ... //same as before
      });
      return false;
})

Answer №1

To stop the default browser behavior, use event.preventDefault() on the client side. Check out more information about preventDefault here

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

Sharing Variables with $(document).ready

I need help understanding why this code is not functioning and how I can fix it. Despite my efforts to use namespaces and IIFEs, I am still unable to make it work. $(document).ready(function() { alert (hi); }); $(document).ready(function() { var hi = ...

Combining HTML, PHP, and Ajax within a single document

Hey everyone! I'm diving back into web programming and challenging myself to create a simple mailing form using just HTML, PHP, and Ajax all within a single file. The goal is to have a self-contained HTML document that doesn't refresh when the fo ...

Implementing Javascript to insert IFRAME into the DOM

I'm looking to incorporate an iframe into my webpage. The iframe needs to link to a specific URL. I attempted to add the following code to my HTML, but it's not functioning as expected: document.createElement('<iframe src='http://ex ...

The powerhouse duo of ASP .NET AJAX and JQuery

I'm attempting to create a basic JQuery example for making AJAX calls to a .NET webservice. However, when using the code snippet below, I am encountering AJAX errors with just a result of 0 instead of any helpful message: Javascript Call function QS ...

can you explain which documents outline the parameters that are passed into the express app.METHOD callback function?

As a beginner in javascript and nodejs, I often struggle with understanding callback functions. One thing that particularly confuses me is determining what arguments are passed into a callback function. Let's consider the following example: app.get( ...

The JSON server middleware is malfunctioning and not functioning as intended

Currently experimenting with node.js/Express/json-server In my effort to monitor (and potentially edit) the request URL being sent to my API json-server, I have implemented the following middleware in my app's server.js file: // Setting up API JSON- ...

Passport fails to store the session

I've researched extensively on this issue, but none of the solutions seem to work for me. I'm currently working with React, Express, and Passport for handling my authentication process. The authentication itself is functioning correctly, includin ...

Get connected to your favorite music on iTunes without the hassle of opening a new window by simply clicking on the

Is there a way to call a link to iTunes (itms://...) without opening a new window? I've tried using window.open but that just opens a new window. Also, $.get('itms://...'); doesn't seem to work for me. Are there any other options avail ...

The UTF-8 encoded string in Node.js displays a mysterious black question mark

I am facing an issue with a CSV file that I receive from my supplier. They have encoded a string using UTF-8, resulting in black question marks appearing. Despite several attempts, I am unable to convert it back successfully. var common = req ...

Removing consecutive pipe symbols in JavaScript

Looking for a way to remove excess pipe characters before a certain pattern in JavaScript. var testString="||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||f_test!!3!!||f_test!!4!!||f_test!!5!!||"; output ="||f_test!!3!!| ...

Cypress and Cucumber collaborate to reinitialize the requests within Next Js

In my upcoming project with Next.js, I am utilizing Cypress for testing a specific page. The objective is to validate two scenarios: 1. Successful outcome and 2. Error handling when a user encounters an issue. Before(() => { return void cy.server() ...

Jest combined with Supertest | Looking out for open handles in Jest

I've been struggling to resolve the "Jest has detected the following 2 open handles" message that appears when running my tests. I seem to have hit a roadblock at the moment. One of the tests I'm trying to fix is as follows: describe('PO ...

Trying to showcase information received from a server using an API

For a school project, I am developing a website that can retrieve weather data (currently just temperature) based on a city or zip code from openweathermap.org using an asynchronous call. I have successfully retrieved the data from the API, but I am strug ...

Observables waiting inside one another

I've encountered an issue where I need to return an observable and at times, within that observable, I require a value from another observable. To simplify my problem, let's consider the following code snippet: public dummyStream(): Observabl ...

An error occurred while trying to insert the data

As a beginner in PHP, I recently attempted to work on a project that involved using AJAX with PHP. The issue I encountered was related to a specific div ID called 'forms2', which contained a form tagged with the class 'create'. Upon cli ...

Issue with jquery curvy corners not functioning properly on Internet Explorer 8

Check out my website at If you view the page in IE8 and then in IE7 compatibility mode, you'll notice a strange issue. The box on the right disappears in IE8 but displays perfectly rounded corners in IE7. I am currently using the jQuery Curvy Corner ...

What is the best way to switch between components in vue.js?

I have created a Dashboard.vue component consisting of two child components: DisplayBooks.vue and sortBooksLowtoHigh.vue. Initially, the sortBooksLowToHigh component is hidden while the displayBooks component is visible by default. The requirement is that ...

IE and Firefox display different responses when encountering an empty XML document

When working with jQuery to read an XML file, I occasionally encounter the situation where the XML is empty. In this case, I anticipate that the error function (no_info) will be triggered because the file is not formatted as expected for the dataType. Int ...

Issues stemming from cross-domain AJAX have resulted in errors with Karma and Jasmine

I've been working on configuring tests that utilize Jasmine and Karma to test my JavaScript code. Karma operates in Node.js and initiates a Chrome browser for testing purposes. Unfortunately, I keep encountering an error message that reads "Chrome 28 ...

Verify the front-end application and authenticate the backend REST API

My project involves developing a REST API and application logic on the client-side, keeping them separate and independent of each other. Now I am looking to implement an authentication system that will automatically authenticate users both on the client-si ...