MEAN Stack Angular js - Multer上传返回http post无效的http响应

时间:2018-02-19 08:44:23

标签: angularjs node.js mongodb mean-stack multer

我试图在MEAN堆栈编程环境中使用npm multer上传图像文件。 Google Chrome浏览器错误控制台会打印' POST http://localhost:3000/api/users/upload net :: ERR_INVALID_HTTP_RESPONSE'。我无法追踪它来自哪里的错误。

以下是控制器中的代码:

(function () {
'use strict';

angular
    .module('app')
    .controller('Account.IndexController', Controller)
    //Added for file upload
    .directive('fileModel', ['$parse', function($parse) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                var parsedFile = $parse(attrs.fileModel);
                var parsedFileSetter = parsedFile.assign;

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

function Controller($window, UserService, FlashService, $scope, FieldsService) {

//Functions for file upload
    $scope.message = false;
    $scope.alert = '';
    $scope.default = '';

    $scope.Submit = function() {
        UserService.UploadFile($scope.file)
        .then(function() {
            $scope.uploading = false;
            $scope.file = {};
        })
        .catch(function (error) {
            //console.log('catched '+error);
            FlashService.Error(error);
        });
    }

    $scope.photoChanged = function(files) {
        if (files.length > 0 && files[0].name.match(/\.(png|jpeg|jpg)$/)) {
            $scope.uploading = true;
            var file = files[0];
            var fileReader = new FileReader();
            fileReader.readAsDataURL(file);
            fileReader.onload = function(e) {
                $timeout(function() {
                    $scope.file = e.target.result;
                    $scope.uploading = false;
                    $scope.message = false;
                });
            };
        } else {
            $scope.thumbnail = {};
            $scope.message = false;
        }
        console.log('photochanged ', $scope.file);
    }

在service.js

(function () {
'use strict';

angular
    .module('app')
    .factory('UserService', Service);

function Service($http, $q) {
    var service = {};

    service.UploadFile = UploadFile;

    return service;

    function UploadFile(file) {
        var fd = new FormData();
        fd.append('myfile', file.upload);
        return $http.post('/api/users/upload', fd, {
            transformRequest: angular.identity,
            headers: { 'Content-Type': undefined}}).then(handleSuccess, handleError);
    }

在路由部分

router.post('/upload', uploadPic);

module.exports = router;

function uploadPic(req, res) {
userService.uploadPic(req, res)
   .then(function () {
        res.sendStatus(200);
    })
    .catch(function (err) {
        res.status(400).send(err);
    });

路由部分调用服务中的另一个函数

var service = {};

service.getAll = getAll;
var express = require('express');
var multer = require('multer');

var storage = multer.diskStorage({
destination: function(req, file, cb) {
    cb(null, 'D:/profile pictures');
},
filename: function(req, file, cb, res) {
    if (!file.originalname.match(/\.(png|jpeg|jpg)$/)) {
        var err = new Error();
        err.code = 'filetype';
        return cb(err);
        console.log('error occured');
    } else {
        console.log('upload successful'); 
        return cb(null, file.originalname);
    }
}
});

var upload = multer({
    storage: storage,
    limits: { fileSize: 10000000 }
}).single('myfile');
service.uploadPic = uploadPic; 

module.exports = service;

function uploadPic(req, res){

var deferred = Q.defer();

upload(req, res, function (err) { //<== Error Occurs Here
    console.log('uploading'); 
    if (err) {
      // An error occurred when uploading
      console.log(err);
      //return res.status(err.status || 400).json({code: err.status || 400, message: err.message || 'Unable to process request.'});
    }  
    // No error occured.
    path = req.file.path;

    deferred.resolve();
});   
return deferred.promise;
}

如何解决此无效的Http响应错误?非常感激。感谢。

0 个答案:

没有答案