2

It's about two days I'm trying to upload images using Nodejs and Expressjs (4.0).

I tryed several middlewares so far, like: Formidable, Blueimp, Busboy, Multer...

With few of these I correctly saved a single image on a temporary folder but the problems comes when I try to upload multiple images.

So, my simple controller look like:

exports.postAccountImages = function(req, res, next) {
  User.findById(req.user.id, function(err, user) {
    console.log(req.files);
  });
};

What I receive is always single Objects like:

{
  files: {
    // data...
  }
}
{
  files: {
    // data...
  }
}

But are not inside an array, so I can not manage all the files incoming using for.

I need to change the name to the images and save these on dynamic folder based on user.id name... but it seems to be too tricky.

I can do it one by one, but I wish to do that on multiple images.

Do you know a middleware or how to use correctly one of the ones I already tried to manage multiple files?

EDIT:

I used Dragzone for the client side. Nothing special here, followed the initial tutorial:

Jade:

#uploader.fileInput
  h3 Drop your images here!

Js:

var myDropzone = new Dropzone(document.body, {
        url: "/account/images", // Set the url
        autoQueue: true,
        paramName: "file",
        uploadMultiple: true,
        autoProcessQueue: true,
        clickable: ".fileInput"
});
4
  • You might want to include what your upload form/code looks like on the client side. Commented Dec 2, 2014 at 17:33
  • Done, I followed a simple tutorial Commented Dec 2, 2014 at 17:36
  • Everything I try to do it limit my file uploads to 2. It seems like I can not upload more that 2 files per time... Commented Dec 2, 2014 at 17:48
  • @AyeyeBrazo Please add my answer as correct if you like it ;) Commented May 27, 2017 at 18:04

2 Answers 2

2

Hope this solves your question, this is my method to multiple upload file:

Nodejs :

router.post('/upload', function(req , res) {

var multiparty = require('multiparty');
var form = new multiparty.Form();
var fs = require('fs');

form.parse(req, function(err, fields, files) {  
    var imgArray = files.imatges;


    for (var i = 0; i < imgArray.length; i++) {
        var newPath = './public/uploads/'+fields.imgName+'/';
        var singleImg = imgArray[i];
        newPath+= singleImg.originalFilename;
        readAndWriteFile(singleImg, newPath);           
    }
    res.send("File uploaded to: " + newPath);

});

function readAndWriteFile(singleImg, newPath) {

        fs.readFile(singleImg.path , function(err,data) {
            fs.writeFile(newPath,data, function(err) {
                if (err) console.log('ERRRRRR!! :'+err);
                console.log('Fitxer: '+singleImg.originalFilename +' - '+ newPath);
            })
        })
}
})

Make sure your has enctype="multipart/form-data"

I hope this gives you a hand ;)

Sign up to request clarification or add additional context in comments.

Comments

1

Hope this solves your question. How To Multiple Image upload using Nodejs And MongoDB

import formidable from 'formidable';
import multiparty from 'multiparty';
import _ from 'lodash'
import fs from 'fs'

async create(req,res){
    let form = new multiparty.Form();
    form.keepExtensions=true;
    form.parse(req,(err,field,files) => {
        if(err)
        {
            return res.status(400).json({
                error:'Image Could Not Uploaded'
            })
        }

        // Multiple Image Store into Database
        let product = new Product(field)
        var imgArray = files.photo;
        var photoarray =  new Array();
        for (var i = 0; i < imgArray.length; i++) {
            if(imgArray.size >= 1000000)  
            {
                res.status(401).json({
                    error:'Image is Less then 1 MB'
                })
            }  
            var newPath = './uploads/product/';
            var singleImg = imgArray[i];
            newPath+= Date.now()+'_'+singleImg.originalFilename;
            readAndWriteFile(singleImg, newPath);     
            photoarray.push(newPath)      
        }
        product.photo=photoarray;

        //Comma Separated Value Store into MongoDB
        var sizestr = field.size.toString()
        var text_arr = sizestr.split(',')
        var sizearray =  new Array();
        for(var i=0;i<text_arr.length;i++)
        {
            sizearray.push(text_arr[i])
        }
        product.size=sizearray;
        product.name=field.name.toString()

        product.save((err,result)=>{
            console.log(err)
            if(err){
                return res.status(400).json({
                    error:errorHandler(err)
                })
            }
            return res.json(result)
        })
    });
    function readAndWriteFile(singleImg, newPath) {

            fs.readFile(singleImg.path , function(err,data) {
                fs.writeFile(newPath,data, function(err) {
                    if (err) console.log('ERRRRRR!! :'+err);
                    console.log('Fitxer: '+singleImg.originalFilename +' - '+ newPath);
                })
            })
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.