nodejs error 'Can not read property' path 'of undefined' [duplicated]

0
router.post('/uploadImage', (request, response, next) => {
    let formidable = require('formidable');
    // parse a file upload
    var form = new formidable.IncomingForm();
    form.uploadDir = '../imagenes/';
    form.keepExtensions = true;
    form.maxFieldsSize = 10 * 1024 * 1024; //10 MB
    form.multiples = true;
    form.parse(request, (err, fields, files) => {
        if (err) {
            response.json({
                result: "failed",
                data: {},
                messege: 'Cannot upload images.Error is : ${err}'
            });
        }

        var arrayOfFiles = [];
        if(files[""] instanceof Array) {
            arrayOfFiles = files[""];
        } else {
            arrayOfFiles.push(files[""]);
        }

        if (arrayOfFiles.length > 0) {
            var fileNames = [];
            arrayOfFiles.forEach((eachFile)=> {
                // fileNames.push(eachFile.path)
                fileNames.push(eachFile.path.split('/')[1]);
            });
            response.json({
                result: "ok",
                data: fileNames,
                numberOfImages: fileNames.length,
                messege: "Upload images successfully"
            });
        } else {
            response.json({
                result: "failed",
                data: {},
                numberOfImages: 0,
                messege: "No images to upload !"
            });
        }
    });
});
    
asked by jose angel 10.12.2018 в 18:57
source

1 answer

0

The problem you have is that files is never an array, always is an object where the keys are the name of the field where they sent the file and the value is an object or an arrangement depending on whether they sent several files in the same field from the client.

This code

var arrayOfFiles = [];
if(files[""] instanceof Array) {
    arrayOfFiles = files[""];
} else {
    arrayOfFiles.push(files[""]);
}

can be written

var arrayOfFiles = Object.keys(files).reduce((curr, key) => {
    const group = files[key]; // Para chequear si es fichero único o arreglo
    if (Array.isArray(group)) {
        curr = curr.concat(group); // Si es arreglo concatenalo al que ya tienes
        // o también [...curr, ...group]
    } else {
        curr.push(group); // Sino agregalo al final
        // o también [...curr, group]
    }
    return curr;
}, []);

Or even more simplified

var arrayOfFiles = Object.keys(files)
    .reduce((curr, key) => Array.isArray(files[key])
        ? [...curr, ...files[key]]
        : [...curr, files[key]]
        , []);

That will generate an arrangement with all the files of your request. Your solution would be

router.post('/uploadImage', (request, response, next) => {
    let formidable = require('formidable');
    // parse a file upload
    var form = new formidable.IncomingForm();
    form.uploadDir = '../imagenes/';
    form.keepExtensions = true;
    form.maxFieldsSize = 10 * 1024 * 1024; //10 MB
    form.multiples = true;
    form.parse(request, (err, fields, files) => {
        if (err) {
            response.json({
                result: "failed",
                data: {},
                messege: 'Cannot upload images.Error is : ${err}'
            });
        }

        var arrayOfFiles = Object.keys(files)
            .reduce((curr, key) => Array.isArray(files[key])
                ? [...curr, ...files[key]]
                : [...curr, files[key]]
                , []);

        if (arrayOfFiles.length > 0) {
            var fileNames = [];
            arrayOfFiles.forEach((eachFile) => {
                // fileNames.push(eachFile.path)
                fileNames.push(eachFile.path.split('/')[1]);
            });
            response.json({
                result: "ok",
                data: fileNames,
                numberOfImages: fileNames.length,
                messege: "Upload images successfully"
            });
        } else {
            response.json({
                result: "failed",
                data: {},
                numberOfImages: 0,
                messege: "No images to upload !"
            });
        }
    });
});
    
answered by 10.12.2018 в 20:16