Multer: req.file always undefined

Created on 18 Sep 2017  路  6Comments  路  Source: expressjs/multer

I am using multer module with express 4 to upload files to my application with a multipart form-data enctype on my form. I have tried all possible solutions to upload the file but in vain. Always a "Cannot read property path of undefined or file of undefined" is returned.

Adding code snippets for my related code as follows:

View

<form method="post" action="/images" enctype="multipart/form-data">
    <div class="panel-body form-horizontal">
        <div class="form-group col-md-12">
            <label for="file" class="col-sm-2 control-label">Browse:</label>
            <div class="col-md-10">
                <input type="file" name="file" id="file" class="form-control">
            </div>
        </div> 

Config File

multer = require('multer');

module.exports = function(app) {
app.use(morgan('dev'));
app.use(multer({
    dest: path.join(__dirname, 'public/upload/temp')}).single('file'));
routes(app);
app.use('/public/', express.static(path.join(__dirname, '../public')));

Controller

var tempPath = req.file.path;
var ext = path.extname(req.file.name).toLowerCase();
var finalPath = path.resolve('./public/upload' + imageUrl + ext);

All 6 comments

having this issue too, seems related to express4. I don't see the full bytes uploaded in the browser network and no file is saved , this is on windows 8, .__dirname shows it's the right place and the folder is already there.

i set header as contentType = false, it worked

If the req.file is null, try req.files.file.
btw, it saving to var folder; not listening to dest options, does it? I have these two problems.

You can get the filename by calling req.file.filename

i have the same issue, i'm using two fields for upload image. But the results "image_ktp_selfie" is same as "image_ktp". Can you help me ?

This problem in here :
image_ktp = result.secure_url;
image_ktp_selfie = result.secure_url;

"multer": "^1.4.1",
"express": "^4.16.3",
"cloudinary": "^1.11.0",

Routes

const express     = require('express');
const router      = express.Router();
const request     = require("request");
const multer      = require("multer");

const storage = multer.diskStorage({
    filename: function(req, file, callback){
        callback(null, Date.now() + file.originalname);
    }
});

const imageFilter = function (req, file, cb) {
    //accept image files only
    if(!file.originalname.match(/\.(jpg|jpeg|png|gif)$/i)) {
        return cb(new Error('Only image files are allowed!'), false);
    }
    cb(null, true);
};

const upload = multer({storage: storage, fileFilter: imageFilter});

const cloudinary = require('cloudinary');
cloudinary.config({
    cloud_name: 'ikutanevent',
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET
});

router.post('/uploadktp' , upload.any(),   (req,res)=>{ 
            var a = req.files[0].path;
            var b = req.files[1].path;
            cloudinary.v2.uploader.upload(a,b, function(error,result) {
                var image_ktp = a;
                var image_ktp_selfie = b;
                    image_ktp = result.secure_url;
                    image_ktp_selfie = result.secure_url;
                console.log("hasil ktp "+image_ktp);
                console.log("hasil selfie "+image_ktp_selfie);
                var userData = {
                    "local.image_ktp" : image_ktp,
                    "local.image_ktp_selfie" : image_ktp_selfie
                }
                if (!req.files) return res.send('Please upload a file')
                User.updateOne({_id:req.user._id},{$set: userData}, function(err, hasil){
                    if(err){
                        res.send(err);
                    } else {
                        res.send("berhasil");
                    }
                });
            });
        }); 

Views

<div class="container">
    <form action="/uploadktp" method="POST" enctype="multipart/form-data">
        <label for="">Upload Scan KTP</label>
        <div class="form-group">
            <input type="file" name="image_ktp" class="form-control" accept="image/*">
        </div>
        <label for="">Upload Selfie with KTP</label>
        <div class="form-group">
            <input type="file" name="image_ktp_selfie" class="form-control" accept="image/*">
        </div>
        <div class="form-group">
            <button class="btn btn-info btn-block">Submit</button>
        </div>  
    </form>
</div>

i set header as contentType = false, it worked

Thanks @deepakpapola it worked. Thanks again.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

donjae picture donjae  路  4Comments

josephstgh picture josephstgh  路  3Comments

Paul-Morris picture Paul-Morris  路  3Comments

ChristianRich picture ChristianRich  路  4Comments

thammarith picture thammarith  路  3Comments