Unable to access file attributes using Multer

Having issues with uploading images from my form using Multer. When an image is inserted, everything functions correctly. However, I encounter an error when no image is selected.

  • Below is the configuration for Multer: all uploaded images are stored in public/images/uploads:
// File upload handling

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'public/images/uploads/')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now()+ '.jpg')
  }
});
var upload = multer({ storage: storage })

My problem arises when attempting to retrieve the value of mainImageName without inserting an image, resulting in the error

cannot get property filename of undefined.

  • Here is the remainder of the code :

    // Submit new post
    router.post('/add', upload.single('mainimage'), function(req, res, next) {
    var title = req.body.title;
    var category = req.body.category;
    var body = req.body.body;
    var author = req.body.author;
    var date = new Date();
    
    if(req.file && req.file.mainimage){
    
        var mainImageName = req.file.filename;
        var mainImageMime = req.file.mainimage.mimetype;
        var mainImagePath = req.file.mainimage.path;
        var mainImageSize = req.file.mainimage.size;
    
    }else{
    
        //if there was no image uploaded!!
        //noimage.png should be placed in public/images/uploads
        mainImageName = 'noimage.png';
    }
    
    console.log(mainImageName); //always returns noimage.png !!
    
    //form validation
    req.checkBody('title', 'You forgot the title').notEmpty();
    req.checkBody('body', 'Please fill in the body').notEmpty();
    
    //check errors
    var errors = req.validationErrors();
    
    if(errors){
    

    var mycategories = []; var categories = db.get('categories'); categories.find({}, {}, function(err, categories) {

        for (i=0; i<categories.length; i++) {
              mycategories[i] = categories[i];
            }
     });
    res.render('addpost', {
            'pageTitle': 'Add Post',
            'errors': errors,
            'title': title,
            'body': body,
            'categories': mycategories
    
        });
    
    } else{
            var posts = db.get('posts');
            //submit Post
            posts.insert({   "title": title, 
                             "body": body,
                             "category": category,
                             "date": date,
                             "author": author,
                             "mainimage": mainImageName 
    
                     }, function(err, post) {
                if (err){
            res.send('There was an issue submitting the post.')
             } else {
                req.flash('success_msg', 'Post Submitted');
                res.location('/');
                res.redirect('/');
             }
             });
    }
    

    });

Answer №1

After investigating, I realized that the problem lied in the condition

if(req.file && req.file.mainimage)
. The issue stemmed from the fact that req.file.mainimage was always undefined. To fix this, I simply modified it to if(req.file), and that resolved the issue successfully.

Here is the revised logic:

if(req.file){

    var mainImageName = req.file.filename;
    var mainImageMime = req.file.mimetype;
    var mainImagePath = req.file.path;
    var mainImageSize = req.file.size;

}else{

    // In case no image was uploaded
    // Place noimage.png in public/images/uploads
    mainImageName = 'noimage.png';
}

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

.htaccess file is causing js and css files to not load

I followed an MVC tutorial by howcode on YouTube, but I encountered an issue where my CSS and JS files were not loading due to the htaccess configuration. .htaccess file: RewriteEngine On RewriteRule ^([^/]+)/? index.php?url=$1 [L,QSA] I attempted vario ...

Customize the jQuery datepicker by assigning a class to the first 17 days

How can I apply a class to only the first 17 days on a jquery datepicker calendar? I've attempted the following code, but it ends up adding the class to every day... beforeShowDay: function(date) { for (i = 0; i < 17; i++) { return [t ...

unique jquery plugin accesses function from external javascript file

As a beginner, I am attempting to create a custom jQuery plugin for which I have a simple HTML form: <form id="registerForm" action = "somepage" method="post" class="mb-sm"> <div class="form-group"> <div class="col-md-12"> ...

The response header Set-Cookie fails to create a cookie in the browser

I'm facing an issue with setting a cookie post user login. The problem seems to occur only in production environment. Upon hitting the /login endpoint, a cookie is returned with a token and other necessary information. if (isPasswordValid === true) { ...

Using Javascript within AEM to update a class upon checkbox selection

I need assistance targeting the 'horizontal-video' class within a div in an AEM component. I am attempting to add a second class called 'flipped' to the div if the author clicks on a checkbox with the ID of 'coral-id-540'. Unf ...

Retrieve the screen width using a JavaScript function and apply it as a percentage

I find myself needing to adjust the size of table elements based on the width of the screen. While I am not well-versed in javascript or html, resolving this issue is crucial. Unfortunately, I did not create the original asp page and have limited ability t ...

Tips for accessing the assigned variable within and outside of a function

Currently, I am working with Webdriverjs and facing an issue. I am trying to assign a variable in a function and then compare that result with some data retrieved from a csv file. However, I am encountering a problem where the value of the data from the ...

The image component is missing the necessary "src" attribute even though a valid src value has been provided as a prop

I'm encountering an issue in Next.JS where a component is not recognizing the image source passed through a prop. I am providing the path of an image named "logo.jpg" from the project's public folder. The image successfully displays when used as ...

What are the steps for scheduling asynchronous tasks using Promises in Node.js?

As a beginner in Javascript, I am struggling to understand how to execute my functions sequentially. My goal is to use Promises to accomplish this task. I am currently following a tutorial on creating a chat bot for Facebook Messenger. Essentially, I want ...

Using object URL to set the source of an image is not functioning properly within the electron framework

Currently working on an electron application ("electron": "^5.0.9", running on Windows 10 version 1903) and dealing with a Node.js buffer (Uint8Array) ("node": "v10.6.0") that holds data in the format of "[255, 216, 255, 224, 0, 16,...)" with a MIME type o ...

Conceal the main div when the nested div does not contain any content

Is there a way to hide the parent div EventsRollup when the child div RelatedEventsList is empty? <div class="EventsRollup"> <span class="EventsRollupTitle">CPR &amp; Health Safety Classes</span><br /><br/> ...

Unable to delete React element by ID as it is undefined

Having some trouble deleting an item by ID with React. Despite the backend routes functioning properly (node and postgresql), every attempt to delete an item results in it reappearing upon page refresh. The command line indicates that the item being delete ...

What is the best way to filter out and combine one array from two arrays in lodash based on their unique properties?

Lodash v 4.17.15 Consider the scenario where two arrays are involved: var users = [{ id: 12, name: Adam },{ id: 14, name: Bob },{ id: 16, name: Charlie },{ id: 18, name: David } ] var jobs = [ ...

Live updates are shown in a format similar to a friend feed or the top tweets on Twitter

I'm currently utilizing PubSubHubbub to obtain the latest updates from the feed. Once the callback URL receives an update, it should be displayed on the webpage in a format similar to Friend Feed or Twitter's top tweets (with content moving down ...

Encountering dependency resolution issues while attempting to install Material UI v5

Encountering a series of dependency resolution errors while attempting to install Material UI. The root cause remains unclear despite previous attempts to resolve issues by upgrading to V5 from V4 due to React compatibility reasons. However, additional con ...

Error: We are facing an issue with new.mongoose.Schema as it is not functioning properly and

I am experiencing an issue with my product.js file. It keeps throwing an error about an unidentified identifier, and whenever I try to fix one problem, another one pops up. I have been struggling to locate the root cause of this error. ...

Using both CASE and MATCH operators within an array in Neo4j's Cypher Query Language (

Using the code snippet below, I am attempting to retrieve all details related to user data where the checked value is either 1 or 0. I have noticed that 'WHERE flight.checked IN check' does not seem to be properly working. Is it appropriate to u ...

When attempting to set a JSON array in state, the resulting JavaScript object does not display correctly

As part of my experimentation with fetch APIs in react, I have set up a server that provides dummy data. In the componentDidMount lifecycle hook of my component, I am making a fetch call to retrieve the data. componentDidMount(){ axios.get('http:// ...

Encountering a null object reference error in AngularJS when using Internet Explorer

Issue: Encountering an error when AngularJS is being loaded in Visual Studio 2015 via an intranet URL. The error is occurring in the AngularJS library at these specific lines: line 7: if(H(b)||Ta(b)) (for angularjs.min.js) line 322: } ...

Prevent dropdown from closing when clicking inside components [react-bootstrap]

I am searching for a solution to hide a drop-down bot by clicking on elements inside it. I am exploring different methods using JQuery. Is it possible to achieve this using JavaScript in combination with react-bootstrap? My current approach involves calli ...