Aer0
Aer0

Reputation: 3907

Images not uploading using ng-file-upload and multer

I am trying to use ng-file-upload and multer for file uploading. My code looks currently like this.

HTML file

<form class="form-inline" ng-submit="startUpload()">
<div class="form-group">
    <fieldset>
        <label for="city" class="hidden"></label>
        <input id="city" class="form-control" type="text" name="city"
               ng-model="city" placeholder="City" />

        <label for="description" class="hidden"></label>
        <input id="description" class="form-control" type="text" name="description"
               ng-model="description" placeholder="Description" />

        <label for="images" class="hidden"></label>
        <input id="images" class="form-control" type="file" name="images"
               placeholder="Images"  accept="image/*"
               ngf-select="uploadFiles($files, $invalidFiles)" />

        <input class="btn btn-custom btn-submit" type="submit" value="Upload">
    </fieldset>
</div>

Angular controller

angular.module('upload').controller('uploadController', function($scope, Upload) {
var uploadUrl = 'http://localhost:1337/api/v1/upload';
var images;

$scope.uploadFiles = function(files, errFiles) {
    images = files;
};

$scope.startUpload = function() {
    var data = {
        location: $scope.city,
        title: 'test title',
        description: $scope.description,
    };

    Upload.upload({
        url: uploadUrl,
        headers : {
            'Content-Type': 'multipart/form-data'
        },
        arrayKey: '',
        data: data,
        files: images
    });
};
});

Backend API

var multer = require('multer');
var upload = multer({ dest : 'source/public/assets/img/test/' });

app.post(versionUrl + '/create-entry', upload.array('images'), function(req, res, next) {
    console.log(req.body) // this contains all text data
    console.log(req.files) // this is always an empty array
});

Since this is the first time I'm doing such a thing, I am totally frustrated it does not work. There are plenty of examples in the internet, providing the exactly same code - still this one does not work for me.

I would be happy about all suggestions, helping me to solve this problem.

Upvotes: 0

Views: 2038

Answers (1)

mscdex
mscdex

Reputation: 106696

You need to instead set images: images in your data object:

var data = {
  location: $scope.city,
  title: 'test title',
  description: $scope.description,
  images: images
};

Upload.upload({
  url: uploadUrl,
  arrayKey: '',
  data: data,
});

Upvotes: 3

Related Questions