无法使用multer从req对象访问req.files

时间:2017-07-31 08:13:39

标签: angularjs node.js express angular-material multer

我正在尝试使用NodeJs脚本将文件上传到服务器。我正在尝试以下事项。

HTML

<md-tab label="Upload log">
    <md-content class="md-padding" id="popupContainer" ng-cloak>
        <h4>Upload a zip file</h4>
            <form ng-submit="$event.preventDefault()">
                <md-input-container class="md-block" flex>
                    <label>Source</label>
                    <md-select name="source" ng-model="log.source" ng-click="getSources()">
                        <md-option ng-repeat="source in sourceInfo" value="{{source.sourceCode}}">{{source.sourceName}}</md-option>
                    </md-select>
                </md-input-container>
                <br>
                <md-input-container class="md-block">
                    <label>Select Batch</label>
                    <input required type="number" step="any" name="rate" ng-model="log.batch" min="1" max="100"/>
                </md-input-container>
                <md-input-container class="md-block">
                    <label>Enter your comments about the log files</label>
                    <textarea ng-readonly="false" ng-model="log.comment" md-maxlength="100" rows="3" md-select-on-focus></textarea>
                </md-input-container>
                <div ng-if="status" id="status">
                    <b layout="row" layout-align="center center" class="md-padding">{{status}}</b>
                </div>
                <input type="file" file-model="log.file" name="inputFile"/>
                <button ng-click="uploadFiles()">Upload</button>
                {{log}}
                <p> </p>
            </form>
    </md-content>
</md-tab>

指令

var logApp = angular.module('logAnalysisApp', ['ngMaterial', 'lfNgMdFileInput', 'ngRoute', 'ngMessages']);
logApp.config(['$routeProvider', '$compileProvider', '$mdThemingProvider', function ($routeProvider, $compileProvider, $mdThemingProvider) {
            $compileProvider.debugInfoEnabled(false);
            $routeProvider
            .when('/login', {
                templateUrl: 'views/login.html',
                controller: 'loginControl'
            })
            .when('/register', {
                templateUrl: 'views/register.html',
                controller: 'registerControl'
            })
            .when('/home', {
                templateUrl: 'views/filemenu.html',
                controller: 'fileUploadCtrl'
            })
            .when('/admin', {
                templateUrl: 'views/adminpanel.html',
                controller: 'adminCtrl'
            })
            .when('/totalreport', {
                templateUrl: 'views/total.html',
                controller: 'totalCtrl'
            })
            .otherwise({
                redirectTo: '/login'
            });
        }
    ])

logApp.constant('config', {
    apiUrl: 'http://localhost:8080',
    serverUrl: 'http://localhost:3000'
})

logApp.directive('fileModel', ['$parse', function ($parse) {
            return {
                restrict: 'A',
                link: function (scope, element, attrs) {
                    var model = $parse(attrs.fileModel);
                    var modelSetter = model.assign;

                    element.bind('change', function () {
                        scope.$apply(function () {
                            modelSetter(scope, element[0].files[0]);
                        });
                    });
                }
            };
        }
    ]);

控制器

logApp.controller('fileUploadCtrl', function ($rootScope, $scope, $timeout, $location, $http, config) {
    $scope.log = {};
    $scope.uploadFiles = function () {

        console.log($scope.log);

        var uploadUrl = "http://localhost:3000/testRef";

        var fd = new FormData();
        for (var key in $scope.log)
            fd.append(key, $scope.log[key]);
        for (var pair of fd.entries()) {
            console.log(pair[0] + ', ' + pair[1]);
        }
        $http.post(uploadUrl, fd, {
            transformRequest: angular.indentity,
            headers: {
                'Content-Type': undefined
            }
        })
        .success(function () {
            console.log("success!!");
        })
        .error(function () {
            console.log("error!!");
        });
    };
});

服务器端编码

var express = require('express')
var app = express()
var multer  = require('multer');
var upload = multer({ dest: './uploads' });
app.post('/testRef', upload.any("inputFile"), function(request, response) {

    console.log(request.files)
    console.log(request.body)
    response.send("Done")
});

当我尝试在控制台中查看request.files时,它显示空白数组,request.body显示为空白对象。但是在我打印$scope.log时的客户端日志中,它显示了相应的内容,在迭代 FormData 变量时,我看到了我发送的所需数据。另外,在我打印时的html {{log}}中,文件数据没有被填充。

欢迎任何类型的帮助。

谢谢。

3 个答案:

答案 0 :(得分:0)

为表格命名并访问req.file(“filename”)

答案 1 :(得分:0)

您必须添加标题'Content-type': 'multipart/form-data'

使用req.files[0],因为您的服务器代码中有upload.any('inputFile')

答案 2 :(得分:0)

我也曾经遇到过同样的问题,但是那是我们的浏览器的工作方式,无法修复。

对此的一种解决方法是在客户端使用javascript捕获提交事件,而不是使用FormData提交并对字段进行排序,以使输入数据位于任何文件之前。

这个技巧对我有用