The request.files property in express-fileupload is consistently coming back as undefined

I am trying to achieve the task of uploading a file from my browser and sending it via POST to an Express.js application, which will then download the file using express-fileupload. Here is the client-side JavaScript code I have written so far:

// Triggered by onclick event of a button
function upload() {
    // Retrieve the selected file (only one can be selected in the input field)
    const file = document.getElementById('file').files[0];

    // Check if a file is selected
    if (!file) {return;}

    // Add the file to a form
    const form = new FormData();
    form.append('file', file);

    // Send the form data using fetchAPI
    fetch('/upload', {
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        method: 'POST',
        body: form
    });
}

The client-side code runs without any errors. The request appears in my network tab. The incoming request from the client is handled by this controller:

import express from 'express'
import fileUpload from 'express-fileupload'

export function uploadPOST(req: express.Request, res: express.Response) {
    if (req.files) {
        console.log('put')
        const file: fileUpload.UploadedFile = req.files.file as fileUpload.UploadedFile
        file.mv(`${settings.storage.path}/${req.app.get('username')}/${file.name}`)
    }
}

In my debugging process, I noticed that req.files is always undefined, although no errors are thrown by the application. I have also included fileUpload and bodyParser.json() in my middleware setup.

Others have faced similar issues and have shared their problems, but none of the solutions provided have resolved my case. I have referred to this tutorial as well:

Answer №1

It's important not to include the Content-Type header in your POST request. Let the browser handle setting it for you. If you manually set the Content-Type, express won't recognize the request as multipart/form-data and won't be able to access the files property of the request.

Additionally, make sure to include the { createParentPath: true } option when using the express-fileupload middleware. This will enable express to create paths and access directories outside of the usual working directory.

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

iterating through the checked values in Angular 4

I need assistance in writing a loop using TypeScript to send each checked employee as a parameter to the postCouncilAbsence function. Can anyone help? component.ts: onattendanceSave(form:NgForm){ this.index = this.attendanceForm.value console.log ...

Accessing a local JSON data file via an AJAX call

function fetchColor() { var promise = $.Deferred(); $.ajax ({ url: 'ajax/color/Red.json', dataType: 'json', type: 'get', success: function(data){ promise.resolve(data); ...

How to ensure unique results when using DFS for Combination Sum?

I am currently tackling the challenge of solving LeetCode #49 Combination Sum. The objective here is to identify all the distinct combinations that add up to the specified target. While it's relatively straightforward to find permutations that result ...

Is it possible to use "/path/{?}" in a path when working with Node.js?

I am new to node.js and I'm working on creating a route that will verify the authorization of all users when the specified endpoint begins with /api. I've learned that an optional value can be indicated using ? like {_id?}, but is it possible to ...

`Node.JS app having issue displaying AngularJS code on Localhost`

I have successfully created a Node.JS application, where I implemented my own HTTP server within the main JS file. The HTML and CSS render correctly on localhost, and even JQuery works when imported via CDN. However, I am facing an issue with displaying ba ...

Exploring logfile usage in JavaScript. What is the best way to structure the log?

Currently, I am developing a Python program that parses a file and records the changes made to it. However, I am facing a dilemma regarding the format in which this information should be saved for easy usage with JavaScript on the local machine. My objecti ...

What is the best way to send multiple parameter values from jQuery to a Laravel controller?

I am facing an issue with my code where I don't understand how to send multiple parameters from jQuery to the controller. Below is the route: Route::get('/listcdix/{id}/detail/{asnumber}', ['as' => 'remindHelper', & ...

Error: The value for 'prepareStyles' property is undefined and cannot be read

Can anyone provide some guidance on this code snippet? I am struggling to understand the error message I am receiving. import React, {PropTypes} from 'react'; import TransactionListRow from './TransactionListRow'; import {Table, TableB ...

Alter the background color of the text input when it is selected for exit

How can I adjust the input field color when text is selected? I'm looking to get rid of the dark grey box highlighting. (Check out the image below) https://i.sstatic.net/OgWaz.gif <div id="ember1102" class="ember-view"> <i class="fa fa ...

Using Ajax to insert data into WordPress

Looking to incorporate data into the WordPress database using Ajax integration. functions.php function addDataToDB(){ global $wpdb, $count; $count = 25; $wpdb->insert( 'custom_table', array( 'slid ...

What is the most effective method for fetching images from MongoDB?

I'm currently working on a web application that uses MongoDB's GridFS to store and retrieve images. However, I'm facing an issue where retrieving images from the database takes significantly longer than expected when a user makes a request. ...

SvgIcon is not a recognized element within the JSX syntax

Encountering a frustrating TypeScript error in an Electron React App, using MUI and MUI Icons. Although it's not halting the build process, I'm determined to resolve it as it's causing issues with defining props for icons. In a previous pro ...

Triggering blur event manually in Ionic 3

Is there a way to manually trigger the blur event on an ion-input element? The ideal scenario would be with an ionic-native method, but any javascript-based workaround will suffice. My current configuration: Ionic: ionic (Ionic CLI) : 4.0.1 (/User ...

How can I use JQuery to enable or disable checkboxes upon loading?

I am looking to implement a feature where the checkboxes are enabled when the .group is checked and disabled when it is unchecked. Although I can toggle between them, I'm facing difficulty in disabling the unchecked checkbox using the .group. Upon lo ...

I'm experiencing an issue where my express-session is being reset with every new request, leading me to question if this is related to the development environment I am using (REACT + EXPRESS)

UPDATE - I have ruled out a development environment issue as the same problem persists in production. Thank you for taking the time to look into this. I've searched through numerous questions and attempted various solutions with no success. To give ...

order by truthiness

I am working with an array of the following class: export class Tests { id: number; name: string; createdAt: any; succress: boolean; constructor(id: number, name: string, createdAt: any, success: boolean) { this.id = id; this.name = nam ...

Retrieve the value of the specific element I have entered in the ngFor loop

I've hit a wall after trying numerous solutions. Here is the code I'm working with: HTML: import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styl ...

Mongoose consistently fails to properly save dates

I have created a Mongoose model and included a birthdate field in the following way: birthdate: { type: Date, required: [true, "Please enter a birthdate"], lowercase: true, validate: [isDate, "Please enter a valid birthdate&q ...

When is the best time and place to break out Yahoo's Mojito Manhattan cocktail mix?

Yahoo! made headlines earlier this month by unveiling their new Mojito framework, set to be open sourced in 2012. I've been eager to learn more about this promising framework but haven't had any success so far. Does anyone know where I can find ...

How can you generate a distinct id value for each element within an ngFor iteration in Angular 4?

I encountered an issue where I must assign a distinct id value to each data row within my *ngFor loop in angular 4. Here is the code snippet: <div *ngFor="let row of myDataList"> <div id="thisNeedsToBeUnique">{{ row.myValue }}</div> & ...