文件上传不工作MEAN堆栈

时间:2016-02-18 16:54:12

标签: javascript angularjs node.js multipartform-data mean-stack

我是MEAN开发的初学者,并尝试使用它来实现CRUD应用程序。最初我使用MEAN成功完成了我的CRUD应用程序。现在我正在尝试使用angular.js上传文件。我知道Angular.js不支持文件上传功能,所以使用https://www.youtube.com/watch?v=vLHgpOG1cW4https://uncorkedstudios.com/blog/multipartformdata-file-upload-with-angularjs 我正在尝试实现此功能。

但不知何故,代码无效并在firebug控制台上发出了一些angular.js错误。

Error: [$injector:unpr] http://errors.angularjs.org/1.5.0/$injector/unpr?p0=multipartFormProvider%20%3C-%20multipartForm%20%3C-%20AppCtrl....so on

以下是我的代码:

应用/公共/ controller.js

var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', 'multipartForm', function ($scope, $http, multipartForm) {
        console.log("Hello World from controller");


        $scope.contact = {};

        var refresh = function () {
            $http.get('/contactlist').success(function (response) {
                console.log("I got the data that I requested");
                $scope.contactlist = response; // This will put data into our html file
                $scope.contact = "";
            });
        };

        refresh();

        $scope.addContact = function () {
            console.log($scope.contact);
            var uploadUrl = '/upload';            
            multipartForm.post('/contactlist', uploadUrl, $scope.contact).success(function (response) {
                console.log(response);
                refresh();
            });
        };

        $scope.remove = function (id) {
            console.log(id);
            $http.delete('/contactlist/' + id).success(function (response) {
                refresh();
            });
        };

        $scope.edit = function (id) {
            console.log(id);
            $http.get('/contactlist/' + id).success(function (response) {
                $scope.contact = response;
            });
        };

        $scope.update = function () {
            console.log($scope.contact._id);
            //$scope.contact means sending all form data to server
            $http.put('/contactlist/' + $scope.contact._id, $scope.contact).success(function (response) {
                refresh();
            });
        };

        $scope.deselect = function () {
            $scope.contact = "";
        };

    }]);

应用/公共/ index.html中

<html ng-app="myApp">
    <head>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

        <!-- Optional theme -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">
        <title>Contact List App</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>


        <div class="container" ng-controller="AppCtrl">
            <div class="panel panel-default">
                <div class="panel-heading"><h4 class="panel-title">Details</h4></div>
                <div class="panel-body">

                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" id="name" placeholder="Name" ng-model="contact.name">
                    </div>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Email address</label>
                        <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email" ng-model="contact.email">
                    </div>
                    <div class="form-group">
                        <label for="Contact">Contact</label>
                        <input class="form-control" placeholder="Contact" ng-model="contact.number">
                    </div>

                    <div class="form-group">
                        <label for="country">Country</label>
                        <select class="form-control" ng-model="contact.country">
                            <option value="">Select</option>
                            <option value="India">India</option>
                            <option value="Australia">Australia</option>
                            <option value="Germany">Germany</option>
                            <option value="Spain">Spain</option>
                            <option value="Japan">Japan</option>
                            <option value="Switzerland">Switzerland</option>
                            <option value="USA">USA</option>
                            <option value="Sri Lanka">Sri Lanka</option>
                            <option value="South Africa">South Africa</option>
                            <option value="England">England</option>
                            <option value="New Zealand">New Zealand</option>                                
                        </select>
                    </div>

                    <div class="form-group">
                        <label for="gender">Gender</label>
                        <div class="radio">
                            <label>
                                <input type="radio" name="gender" id="optionsRadios1" value="Male" ng-model="contact.gender">
                                Male
                            </label>
                            &nbsp;&nbsp;
                            <label>
                                <input type="radio" name="gender" id="optionsRadios2" value="Female" ng-model="contact.gender">
                                Female
                            </label>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="education">Education</label>
                        <div class="checkbox">
                            <label>
                                <input type="checkbox" name="education" ng-model="contact.education.MCA">
                                MCA
                            </label>
                            &nbsp;&nbsp;
                            <label>
                                <input type="checkbox" name="education" ng-model="contact.education.BE">
                                BE
                            </label>
                            &nbsp;&nbsp;
                            <label>
                                <input type="checkbox" name="education" ng-model="contact.education.ME">
                                ME
                            </label>
                            &nbsp;&nbsp;
                            <label>
                                <input type="checkbox" name="education" ng-model="contact.education.BCA">
                                BCA
                            </label>
                        </div>
                    </div>

                    <div class="form-group">
                        <label>Avatar</label>
                        <input type="file" file-model="contact.file">                        
                    </div>

                    <div class="well well-lg text-center bg-gray">
                        <button class="btn btn-primary" ng-click="addContact()">Add Contact</button>
                        &nbsp;&nbsp;
                        <button class="btn btn-info" ng-click="update()">Update</button>
                        &nbsp;&nbsp;
                        <button class="btn btn-info" ng-click="deselect()">Clear</button>
                    </div>

                </div>

                <h4>Listing</h4>
                <input type="text" class="form-control" ng-model="contact.names" placeholder="Instant result search">
                <table class="table table-bordered">
                    <tr>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Number</th>
                        <th>Country</th>
                        <th>Gender</th>
                        <th>Education</th>
                    </tr>
                    <tr ng-repeat="contact in contactlist| filter:contact.names|orderBy:-1">
                        <td>{{contact.name}}</td>
                        <td>{{contact.email}}</td>
                        <td>{{contact.number}}</td>
                        <td>{{contact.country}}</td>
                        <td>{{contact.gender}}</td>
                        <td>
                            {{contact.education}}
                        </td>
                        <td>
                            <button class="btn btn-danger" ng-click="remove(contact._id)">Remove</button>
                            &nbsp;&nbsp;
                            <button class="btn btn-warning" ng-click="edit(contact._id)">Edit</button>
                        </td>
                    </tr>
                </table>
            </div>



            <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
            <script src="controllers/controller.js"></script>
            <script src="services/multipartForm.js"></script>
            <script src="directives/fileModel.js"></script>

    </body>
</html>

应用/公共/服务/ multipartForm.js

myApp.service('multipartForm', ['$http', function ($http) {
    this.post = function (uploadUrl, data) {

        var fd = new FormData();

        for (var key in data)
            fd.append(key, data[key]);

        $http.post(uploadUrl, fd, {
            transformRequest: angular.indentity,
            headers: {'Content-Type': undefined}
        });

    };
}]);

最后在Node / Express Side:app / server.js

var express = require('express');
var app = express(); // using this we can use commands, function of express in this (server.js) file
var mongojs = require('mongojs');
var db = mongojs('contactlist', ['contactlist']); // Means which mongodb database & collection we are going to use
var bodyParser = require('body-parser');
var multer = require('multer');

// To test whether server is running correctly
/* app.get("/", function(req, res){
 res.send("Hello world from server.js");
 }); */

app.use(express.static(__dirname + "/public")); // express.static means we are telling the server to look for static file i.e. html,css,js etc.
app.use(multer({dest: './uploads/'}).single('photo'));
app.use(bodyParser.json()); // To parse the body that we received from input


//This tells the server to listen for the get request for created contactlist throughout
app.get('/contactlist', function (req, res) {

    console.log("I received a GET request");

     //Creating an array of above data
     var contactlist = [person1, person2, person3];
     // its going to respond to the GET request by sending back contactlist data in JSON format which controller can use
     res.json(contactlist);


    db.contactlist.find(function (err, docs) {
        console.log(docs);
        res.json(docs);
    });

});

// listens for the POST request from the controller
app.post('/contactlist', function (req, res) {
    console.log(req.body);
    db.contactlist.insert(req.body, function (err, doc) {
        res.json(doc);
    });
});

app.delete('/contactlist/:id', function (req, res) {
    var id = req.params.id; // to get the value of id from url
    console.log(id);
    db.contactlist.remove({_id: mongojs.ObjectId(id)}, function (err, doc) {
        res.json(doc);
    });
});

app.get('/contactlist/:id', function (req, res) {
    var id = req.params.id;
    console.log(id);
    db.contactlist.findOne({_id: mongojs.ObjectId(id)}, function (err, doc) {
        res.json(doc);
    });
});

app.put('/contactlist/:id', function (req, res) {
    var id = req.params.id;
    console.log(req.body.name);
    db.contactlist.findAndModify({
        query: {_id: mongojs.ObjectId(id)},
        update: {$set: {
                name: req.body.name,
                email: req.body.email,
                number: req.body.number,
                country: req.body.country,
                gender: req.body.gender,
                education: req.body.education
            }}, new : true}, function (err, doc) {
        res.json(doc);
    });
});

app.listen(3000);
console.log("Server running on port 3000");

任何帮助将不胜感激:)

0 个答案:

没有答案