When accessing files.fileName.path in formidable, it may result in returning undefined

The server is unable to save the file. The path property is giving back an undefined value.

const saveImage = (req, res) => {
  const form = formidable.IncomingForm();

  form.uploadDir = `./images`;
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    if (err) {
      return res.json("There was an error parsing the form");
    }

    console.log(files.image.path);
    res.json(files.image.path);
  });
};

Answer №1

function handleProfileUpload(request, response) {

    const settings = {
    uploadDirectory: `./photos`,
    maintainFileExtensions: true,
  };

  const formProcessor = new formidable.IncomingForm(settings);

  formProcessor.parse(request, (error, formData, receivedFiles) => {
    if (error) {
      return response.json("Formidable failed to process the form");
    }

    const {fileLocation, originalName, updatedName, fileSize, fileType} = receivedFiles.picture;
    //'picture' represents the file name... files.fileName 
    console.log(updatedName, "...");
   
    response.json(updatedName);
  });
};

Explore the upgrade process from Version 1 to Version 2 or Version 3

Answer №2

I am encountering a similar issue with the following code snippet:

const [afields, afiles] = await form.parse(req);

The issue arises because the field name below "afiles" keeps changing, it could be "files", "image", "upload", and so on, which is puzzling to me...

To tackle this problem, I decided to iterate through the "afiles" object:

const uploadedFiles = [];
        
const afilesValues = Object.values(afiles);
const nbAfilesValues = afilesValues.length;
for( let i=0; i<nbAfilesValues; i++){
    const value1 = afilesValues[i];

    if (typeof value1 == 'object' && value1.constructor.name == 'PersistentFile'){
        uploadedFiles.push(value1);
        continue;
    }
            
    if (typeof value1 == 'object' && value1.constructor.name == 'Array'){
        const nb2 = value1.length;
        for(let i2=0; i2<nb2; i2++){
            const value2 = value1[i2];
                    
            if (typeof value2 == 'object' && value2.constructor.name == 'PersistentFile'){
                uploadedFiles.push(value2);
                continue;
            }
        }
        continue;
    }
}

This way, all the uploaded files will be stored in the "uploadedFiles" array...

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

Transmit a data point from JavaScript to PHP

I am looking to transfer the address value to a different PHP page <script> var userAddress = place.formatted_address; document.getElementById('af').innerHTML = userAddress; </script> ...

Acquire the Information from a Textarea That Has Been Edited by the User

My challenge lies in taking user-entered text from a content editable textarea and sending it via POST request, but the fields edited by the user are returning with an empty textContent. The code snippet below shows that each .entryRow (obj) contains multi ...

Creating an error handler in PHP for dynamically adding or removing input fields is a crucial step in ensuring smooth and

I designed a form with multiple fields, including a basic input text field and dynamic add/remove input fields. I successfully set the first field as required using PHP arguments, but I'm struggling to do the same for the additional fields. I need as ...

Verify the definition of the checkbox

I'm attempting to determine whether a checkbox is defined and unchecked. When the page loads, my checkbox is disabled and I receive an error indicating that it is undefined. I attempted to create a condition to prevent the error but was unsuccessful. ...

Ways to update a ViewComponent using Ajax in Asp.net Core 3.1

How can I make FavoriteComponent refresh when the "a" tag is clicked? Html : <div id="favorite-user"> @await Component.InvokeAsync("FavoriteComponent") </div> Action Html : <a id="add-fav" onclick="addfavorite('@pr ...

What is the best way to manage the loading and unloading of JavaScript within dynamically loaded partial pages?

Utilizing jQuery and history.js, I manage seamless transitions between partial pages to prevent entire document reloads. Some of these partial pages include unique javascript files. Despite successful page transitions, remnants of executed javascript linge ...

Automatically save user input in form fields with the help of jQuery and AJAX technology

I'm working on a form that has various input fields, and I need the data entered by the user to be automatically stored in the database every minute. After the user submits the request, it will be processed in a struts file where database interactions ...

Is it necessary to confirm the validity of url.format(urlObject)?

I have been exploring the NodeJS URL API and am particularly interested in the url.format(urlObject) method. My goal is to develop a function that first validates the urlObject before using the format function, and throws a TypeError if any of the key/valu ...

Tips for showcasing axios data on Vue components

I'm just starting out with Vue.js and I'm struggling to grasp how it all works. I have a function that sends data to the server and receives a response using axios. However, when I try to display the response using a variable, something seems to ...

Display HTML components depending on an object's property using AngularJS

Here is the code I have created to display a simple drop down list: var products = [ { "id": 1, "name": "Product 1", "price": 2200, "category": "c1" }, { "id": 2, "name": "Product 2", "p ...

Working with arrays and data to populate tables and cross tables using a single Eloquent Model in Vue and Laravel

There are three tables in the database: species, panel, and a cross table called species_panel. The relationship between them is that one panel can contain multiple species, so a one-to-many relationship is used. Data needs to be inserted into the panel ta ...

ES6 - Error of duplicate declaration when importing files

Before ES6: var stream = require("./models/stream"); var stream = require("./routes/stream"); The above code works without any issues. With ES6: import stream from './models/stream'; import stream from './routes/stream'; But now, a ...

In the world of NodeJS, the 'Decimal' module functions just as effectively when written as 'decimal'

I recently installed and started using the package decimal.js in my NodeJS project. If you're interested, you can find more information on this package here. What I found interesting is that while all the examples recommend using Decimal, I also not ...

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 ...

Implementing MUI createTheme within Next.js

After switching from material-UI version 4 to version 5.5.0 in my project, I encountered issues with createTheme. The colors and settings from the palette are not being applied as expected. Current versions: next: 11.0.0 react: 17.0.2 mui : 5.5.0 theme. ...

Auto-selecting the first item in a CSS menu when the switcher is tapped on mobile devices

Struggling with a responsive CSS menu on my website, . The switcher on mobile seems to automatically click the first item in the menu (Home) as I open it, redirecting me instantly. When setting the link to "#" everything is fine, but then I lose the home l ...

Sending data from PHP to JavaScript using AJAX

I'm encountering an issue trying to pass data from a PHP file to a JavaScript file using echo. My PHP file contains the following code snippet: <?php ...establishing connection and retrieving list from database... for($i=0;$i<sizeOf($li ...

Scrolling the bottom of a PDF object element in HTML using JavaScript - a simple tutorial

There is a Pdf object displayed on my website <object data="data/test.pdf" type="application/pdf" width="700" height="900"> </object> I'm trying to automatically scroll this pdf to the last page when the page loads. I've found tha ...

How to retrieve the length of data in Angular without relying on ng-repeat?

I am currently working with Angular and facing a challenge where I need to display the total length of an array without using ng-repeat. Here is the situation: I have a default.json file: { { ... "data": [{ "name":"Test", "erro ...

Is it possible to customize the appearance of the selected item in a select box? Can the selected value be displayed differently from the other options?

My current project involves working with the antd' select box. I have been trying to customize the content inside the Option which usually contains regular text by incorporating some JSX into it. The output currently looks like this: https://i.sstati ...