【问题标题】:Images not uploading using ng-file-upload and multer图片未使用 ng-file-upload 和 multer 上传
【发布时间】:2016-01-07 16:44:53
【问题描述】:

我正在尝试使用ng-file-uploadmulter 进行文件上传。我的代码目前看起来像这样。

HTML 文件

<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.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
    });
};
});

后端 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
});

因为这是我第一次做这样的事情,我很沮丧它不起作用。互联网上有很多示例,提供完全相同的代码 - 仍然对我不起作用。

我会很高兴收到所有建议,帮助我解决这个问题。

【问题讨论】:

    标签: angularjs node.js express multer ng-file-upload


    【解决方案1】:

    您需要在 data 对象中设置 images: images

    var data = {
      location: $scope.city,
      title: 'test title',
      description: $scope.description,
      images: images
    };
    
    Upload.upload({
      url: uploadUrl,
      arrayKey: '',
      data: data,
    });
    

    【讨论】:

    • 嗯,这似乎工作了。您能解释一下为什么我需要将图像存储在“图像”字段中吗?我以为我必须使用“文件”字段。
    • files 不是 Upload.upload 的选项,因此 files: images 将被忽略。
    猜你喜欢
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 2013-06-17
    • 2017-08-16
    • 2016-01-08
    • 1970-01-01
    • 2017-01-26
    • 2015-12-11
    相关资源
    最近更新 更多