JavaScript method of retrieving an object inside an array nested within another object via multer

Below is my custom multer function to handle file uploads -

const storage = multer.diskStorage({
  destination: (req, file, callback) => {
    let type = req.params.type;
    let path = `./data/${type}`;
    fs.mkdirsSync(path);
    callback(null, path);
  },
  filename: (req, file, cb) => {
    const ext = mime.extension(file.mimetype);
    const random = Math.floor(Math.random() * (9999 - 1000 + 1)) + 1000;
    cb(null, `${Date.now()}-${random}.${ext}`);
  },
});

Here is how the router is configured -

router.post("/", auth, multer({ storage }).fields([{ name: 'image', maxCount: 1 }, { name: 'video', maxCount: 1 }]), addMovie); 
When I log console.log(req.files), this is what I see:

[Object: null prototype] {
  image: [
    {
      fieldname: 'image',
      originalname: ' .png',
      encoding: '7bit',
      mimetype: 'image/png',
      destination: './data/undefined',
      filename: '1631293039713-7613.png',
      path: 'data\\undefined\\1631293039713-7613.png',
      size: 13133
    }
  ],
  video: [
    {
      fieldname: 'video',
      originalname: 'file_example_MP4_480_1_5MG.mp4',
      encoding: '7bit',
      mimetype: 'video/mp4',
      destination: './data/undefined',
      filename: '1631293039720-3601.mp4',
      path: 'data\\undefined\\1631293039720-3601.mp4',
      size: 1570024
    }
  ]
}

I have both an image and a video being uploaded. Now, I want to access the properties within these objects but I'm not sure how.

After trying req.files.image[0], here is the error message I received -

Property 'image' does not exist on type '{ [fieldname: string]: File[]; } | File[]'. Property 'image' does not exist on type 'File[]'.ts(2339)

Answer №1

One approach to consider is accessing the first image file using (req as any).files.image[0]. Unfortunately, dealing with typings for the req object can be a bit cumbersome.

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

IE/Firefox returning empty value for Ajax requests

After spending two days trying to solve the issue, I still can't figure out why this code is failing in IE (v11) and Firefox while working fine in Chrome. I have read many questions on similar topics involving caching problems with multiple Ajax call ...

What steps can I take to resolve the issue of the Error value not being iterable?

I encountered an issue in my table where I get the error message value is not iterable when there is no value to iterate through. How can I handle this error in my code? Snippet of Code: if (null != data && data) { data = data.map((item) => ...

Definition for the type react-navigation-v6 <Stack.Group>

I'm having trouble figuring out the proper type definition for a Stack group that includes screens (refer to TestStack.Group and the nested TestStack.Screen). The navigation stack: const TestStack = createNativeStackNavigator<TestStackParamList> ...

Learn how to dynamically set the "selected" option in Vue based on object data

I've done some digging on SO but haven't found exactly what I need. So, here's the situation - I've got a sorting function in progress. I have an array of date ranges (PayPeriods) that I want to render into a select with option compone ...

Is it possible to set the input form to be read-only?

I need to create a "read-only" version of all my forms which contain multiple <input type="text"> fields. Instead of recoding each field individually, I'm looking for a more efficient solution. A suggestion was made to use the following: <xs ...

How come I can't capture discord.js promise rejections within event callbacks?

As I delve into creating a discord bot, I encountered an interesting problem. To simplify things, here is a snippet that encapsulates the issue at hand: const Discord = require('discord.js'); const client = new Discord.Client(); client.on(&apo ...

Angular2 has encountered a malfunction with the chart feature

My attempt to create a Bar Chart with this GitHub repository is not working in Chrome. You can view my code on Plunker. Can someone help me identify the issue? Below is the updated code: app.ts import {Component, Pipe, PipeTransform} from 'angular2 ...

Locate a specific option that matches the value of the selected data-status and set it as "selected" using jQuery

Currently, I am facing an issue where I need to load 2 separate ajax responses into a select dropdown. The select dropdown will have a data-status attribute, and my goal is to loop through the options to find the one that matches the value of the select da ...

How can we dynamically update property values in a ngFor loop by utilizing the click method?

Here is a TypeScript file I am working with: <md-card style="display: inline-block;" *ngFor="let people of peoples"> <p> {{people.name}} </p> <p *ngIf="people.showAge"> {{people.age}} </p> < ...

Avoid repeated appending of data in JavaScript and HTML

I am working with an HTML table and I need to ensure that the values in the second column do not repeat within the grid. Below is the JavaScript code I have written for this purpose: var $addedProductCodes = []; function getProductData(value){ $t ...

The functionality of JSON.stringify involves transforming colons located within strings into their corresponding unicode characters

There is a javascript string object in my code that looks like this: time : "YYYY-MM-DDT00:00:00.000Z@YYYY-MM-DDT23:59:59.999Z" When I try to convert the object to a string using JSON.stringify, I end up with the following string: "time=YYY ...

Discover the process of retrieving an image from the backend with React and Node.js

Hey there! I'm currently working on a Housing blog using ReactJS and NodeJS. One of the tasks I tackled was creating a login controller in NodeJS to send user details, including the image path from the database, to the frontend. The image path is sto ...

There seems to be a syntax error in the AngularJS/Bootstrap code, with an unrecognized expression

Hey there, I'm currently working on developing an application using Angular and Bootstrap. I've successfully implemented ui.router for routing purposes, but I've encountered an issue when loading the Bootstrap library. The console is showing ...

The 'component' property is not found in the 'IntrinsicAttributes' type in this context

I am facing an issue with a component that is not compiling properly: export default function MobileNav({routes, currentRouteIndex, handlePressedRoutedIndex}: MobileNavProp) { ... return ( <React.Fragment> ... ...

What does the "start" script do in the package.json file for Angular 2 when running "concurrent "npm run tsc:w" "npm run lite"" command?

What is the purpose of concurrent in this code snippet? "scripts": { "tsc": "tsc", "tsc:w": "tsc -w", "lite": "lite-server", "start": "Concurrent npm run tsc:w npm run lite" } ...

Having difficulty installing the yarn package from GitHub

I'm attempting to install a GitHub package using yarn. I've tried this process many times before, but I have not been successful with this particular repository: https://github.com/coolwanglu/pdf2htmlEX I have already attempted the following w ...

How to implement a responsive menu using the onPress attribute of TouchableOpacity

Looking to implement a profile picture upload feature with the ability to choose between getting an image from the camera (using getMediaFromCamera) or selecting one from the gallery (using getMediaFromImageLibrary). I currently have a TouchableOpacity set ...

The functionality of CDK Drag Drop is not accurately adjusting the placement of images

I have implemented an image gallery and am working on rearranging the position of the images using the Drag & Drop cdk library. However, I am facing an issue where the swapping of images does not always occur correctly; sometimes when attempting to exchan ...

Enhancing Chat: Updating Chat Messages in Real-Time with Ember.js and Firebase

I recently started working with ember.js and firebase. Right now, I have successfully implemented a feature to post messages and view them in a list format as shown below: //templates/show-messages.hbs {{page-title "ShowMessages"}} <div clas ...

Struggling to iterate through the children of a variable with the help of express-handlebars?

Currently, I am in the process of developing an application using Javascript along with express, express-handlebars, and MySQL. One of my main tasks is to establish a route that follows the pattern '/viewowner/:ID/scoreboards/:year' where ID sig ...