我需要使用angularJS,NodeJS和ExpressJS将文件上传到服务器

时间:2018-06-04 09:30:05

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

我尝试关注此链接https://ciphertrick.com/2015/12/07/file-upload-with-angularjs-and-nodejs/,但收到错误

节点版本为4.4.7,ngFileUpload中的modulerr错误

用于app.js中的文件上传

        var multer = require('multer');
        var storage = multer.diskStorage({ //multers disk storage settings
         destination: function (req, file, cb) {
        cb(null, '../../../../uploads/')
    },
    filename: function (req, file, cb) {
        //var datetimestamp = Date.now();
       // cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length - 1])
        cb(null, file.originalname)
    }
});
var upload = multer({ //multer settings
    storage: storage
}).single('file');

将上传文件的API路径

app.post('/upload', function (req, res) {
    upload(req, res, function (err) {
        console.log("inside upload");
        if (err) {
            console.log("inside upload err");
            res.json({ error_code: 1, err_desc: err });
            return;
        }
        res.json({ error_code: 0, err_desc: null });
    })
});

角度控制器

    .module('CIController', ['ngMaterial', 'ngAnimate', 'ngAria', 'ngMessages', 'Alertify', 'ngFileUpload',])

    .controller('childController', ['$scope', '$location', '$q', '$timeout', '$log', 'CIFactory', 'ClientConfig', 'Alertify', 'Upload', '$window', function ($scope, $location, $q, $timeout, $log, CIFactory, ClientConfig, Alertify, Upload, $window) {
.....
$scope.submitfile = function () { //function to call on form submit
            if ($scope.indexForm.$valid && $scope.BuildModel.file) { //check if from is valid
                var isuploaded = $scope.uploadfiletoserver($scope.BuildModel.file); //call upload function
            }
        }
        $scope.uploadfiletoserver = function (file) {
            Upload.upload({
                url: '/upload', //webAPI exposed to upload the file
                data: { file: file } //pass file as data, should be user ng-model
            }).then(function (resp) { //upload function returns a promise
                if (resp.data.error_code === 0) { //validate success
                    console.log("inside upload controller");
                    $window.alert('Success ' + resp.config.data.file.name + 'uploaded. Response: ');
                    return ClientConfig.BOOL_TRUE;
                } else {
                    $window.alert('an error occured');
                    return ClientConfig.BOOL_FALSE;
                }
            }, function (resp) { //catch error
                console.log('Error status: ' + resp.status);
                $window.alert('Error status: ' + resp.status);
                return ClientConfig.BOOL_FALSE;
            }, function (evt) {
                console.log(evt);
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
                $scope.progress = 'progress: ' + progressPercentage + '% '; // capture upload progress
            });
        };

在HTML中

<form name="indexForm" invalidfieldfocus novalidate id="indexForm" autocomplete="off" enctype="multipart/form-data">
    <div>
        <input type="file"                                                                ngf-select                                                                           ng-model="$parent.BuildModel.file"                                                                           name="file" ngf-max-size="20MB" />                                                                
        <i ng-show="indexForm.file.$error.required">*required</i><br>
        <i ng-show="indexForm.file.$error.maxSize">File too large                                                                        {{indexForm.file.size / 1000000|number:1}}MB: max 20M
        </i>                                                                
        <p>{{indexForm.file.progress}}
 </div>

1 个答案:

答案 0 :(得分:0)

现在没有错误。

  1. 确保ng-file-upload所有JavaScript文件都包含在HTML中。

  2. 在控制器中包含ngFileUpload,如上面代码部分所示。

  3. 安装ng-multer并编写如上所示的所需功能,我们提到的路径应该已经创建了文件夹,否则会引发错误。