wurstbrotrest
wurstbrotrest

Reputation: 329

node-multer: Form submission fails when there is no file to upload

This HTML form below is (among other things) uploading a file to a server using express.js and multer. It works fine, if a file is chosen, but not if the file is left out.

<form id="uploadform" method="post" action="/upload" enctype="multipart/form-data">
    <p> Description: <input type="text" name="description"></p>
    <p><input type="file" name="img"></p>
    <p><input id="submit_upload" type="submit" value="Submit"></p>
</form>

My Node.js application includes the middleware multer.

var express = require('express');
var app = express();
var multer = require('multer');

app.use(multer(
    {
        dest: './public/img/',
        rename: function (fieldname, filename) {
            return filename + Date.now();
        }
    }));

When the form is submitted, I will be redirected to /upload, as it is defined in the HTML-Upload form with action="/upload". In my Node.js script the form entries will be handled as shown below:

app.post('/upload', function (req, res) {
    var form_description = req.body.description;
    var form_datei = JSON.stringify(req.files.img.name);
    form_datei = form_datei.substring(1, form_datei.length - 1);
    //  insert operations into database get placed here
    res.redirect('/');
});

If I don´t select a file in the form and submit it only with inserted text, not even the text will be submitted. Instead my console and browser window display a long error message starting as you can see below:

TypeError: Cannot read property 'name' of undefined

How can I make the form submit if no file is selected? The file upload should be optional. Thanks for your help!

Upvotes: 2

Views: 4047

Answers (1)

victorkt
victorkt

Reputation: 14572

The problem is when you try to retrieve the image name in req.files.img.name. Since req.files.img will return undefined, you can't read the property there.

Check if a file was submitted before trying to use it:

app.post('/upload', function (req, res) {
    var form_description = req.body.description;
    if(req.files.img) {
        var form_datei = JSON.stringify(req.files.img.name);
        form_datei = form_datei.substring(1, form_datei.length - 1);
        //  insert operations into database get placed here
    }
    res.redirect('/');
});

Upvotes: 5

Related Questions