question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Upload multiple files with multer?

See original GitHub issue

I just can’t figured whats wrong why my codes below. I try to upload multiple files. The problem is that i had an “UNEXPECTED FIELD”… I can make it to upload single file just fine, If I put upload.single('image') but I can’t make it upload multiple files. So what’s wrong?

html <input id="file" type="file" class="form-control" placeholder="Imagen" name="image" multiple>

component.js

var payload = new FormData();
var files =  $('#file')[0].files

        for (key in $scope.producto) {
            payload.append(key, $scope.producto[key])
            console.log($scope.producto[key])
        }


     if (files.length > 0) {

            for (var i = 0; i < files.length; i++) {
                    var file = files[i];
                    console.log(file)
                    console.log(files.length)
                    payload.append('image', file);
                }
            }
       $http.post('http://localhost:5001/api/v1/articles', payload, {
            transformRequest: angular.identity,
            headers: { "Content-Type": undefined },
        }).then(function (response) {
            $location.path("/")
        })

And here 's the server part: app.js

const multer = require('multer')
const storage = multer.diskStorage({
    destination : function(req, file, cb){
        cb(null, './uploads/');
    },
filename : function(req, file, cb){
    cb(null, new Date().toISOString() + file.originalname)
}

})

const upload = multer({storage : storage, limits: {
    fileSize : 1024 * 1024 * 5 
}})

.post(‘/api/v1/articles/’, upload.array(‘image’, 2 ), controllerArticle.postArticles)`

ControlletArticle.js


function postArticles(req, res) {
    // console.log(req.file)
if (req.file) {

const nvo = new articulos({
    name: req.body.name,
    price: req.body.price,
    condition: req.body.condition,
    brand: req.body.brand,
    productImage: req.file.path
})
nvo.save((err, productStored) => {
    if (err) res.status(500)

    res.status(200).send({ nvo: productStored })
})
}
}

modelarticle.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema;

const articulos = Schema({
    name:  String,
    price: Number,
    condition: String,
    brand: String,
    productImage:  { type: String }
})

module.exports = mongoose.model('articulos', articulos)

I have tried so far:

Change upload.array() to upload.any(),and doesn’t work… any help? thanks!

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

61reactions
LinusUcommented, Aug 27, 2018

Instead of upload.single('image') you want to do upload.array('image'), and then look at req.files instead of req.file.

7reactions
tohedulcommented, Sep 12, 2020

If you want to upload multiple files with one single field then you have to use upload.array(‘image’, 2). Else if you want to upload files with multiple fields then you have to use upload.fields([{name:‘image’, maxCount: 1}, {name: ‘banner’,maxCount: 1}]) . You can access file by req.files[‘image’][0] req.files[‘banner’][0] as well Hope that will help.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Uploading multiple files with Multer - Stack Overflow
Uploading multiple files with Multer ; form class='new-project' action='/projects' method='POST' enctype="multipart/form-data"> ; label for='file' ...
Read more >
How to upload multiple files in Node.js - BezKoder
Create middleware for upload multiple files ... Inside middleware folder, create upload.js : const util = require("util"); const path = require(" ...
Read more >
How to Upload Multiple Files in Multiple Form Fields in Node ...
How to Upload Multiple Files in Multiple Form Fields in Node.js and Express Using Multer LibraryDownload the full source code of application ...
Read more >
How to Upload Multiple Files Using Node.js - CodeForGeek
Multer is one of the easy node modules you can use with Express for file upload. It allows you to add various validation...
Read more >
Upload Files from Multiple Fields using Multer | by Aakash Jha
Upload Files from Multiple Fields using Multer · Step 1: Install dependencies · 3.1 Defining storage · Step 4: Create that multer middleware,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found