Friday, 21 April 2017

Error Uploading File Using multer

I am trying to create a WebApp where a user can upload his profile pic from the profile page. I am using MEAN Stack and uploading file using multer.

Here is my code for CLIENT VIEW

 <div class="col-xs-8 vn-right-pane">
        <h1>Profile</h1>
        <form class="form-horizontal" enctype="multipart/form-data">
            <div class="form-group">

        <label for="first">First Name</label>
        <div class="input-group">
        <span class="input-group-addon">
                    <i class="glyphicon glyphicon-option-horizontal"></i>
                </span>
            <input ng-model="model.navigatedUser.firstName"
                   id="first"
                   class="form-control"
                   type="text"
                   placeholder="First Name"/>
        </div>


        <label for="last">Last Name</label>
                <div class="input-group">
        <span class="input-group-addon">
                    <i class="glyphicon glyphicon-option-horizontal"></i>
                </span>
        <input ng-model="model.navigatedUser.lastName"
               id="last"
               class="form-control"
               type="text"
               placeholder="Last Name"/>
                </div>

        <label for="email">Email</label>
                <div class="input-group">
        <span class="input-group-addon">
                    <i class="glyphicon glyphicon-envelope"></i>
                </span>
        <input ng-model="model.navigatedUser.email"
               id="email"
               class="form-control"
               type="email"
               placeholder="Email"/>
                </div>

        <label>Username</label>
                <div class="input-group">
        <span class="input-group-addon">
                    <i class="glyphicon glyphicon-user"></i>
                </span>
        <input ng-model="model.navigatedUser.username"
               class="form-control"
               type="text"
               placeholder="Username"/>
                </div>

                <label>Profile Image</label>
                <div class="input-group">
        <span class="input-group-addon">
                    <i class="glyphicon glyphicon-upload"></i>
                </span>
                    <input name='myFile'
                           type='file'
                           class="form-control">
                </div>

        <label>Phone Number</label>
                <div class="input-group">
        <span class="input-group-addon">
                    <i class="glyphicon glyphicon-phone"></i>
                </span>
        <input ng-model="model.navigatedUser.phone"
               class="form-control"
               type="text"
               placeholder="Phone Number"/>
                </div>





        <a ng-click="model.deleteUser(model.navigatedUser)"
           class="btn btn-warning btn-block">
            Unregister
        </a>

        <a ng-click="model.updateUser(model.navigatedUser)"
           class="btn btn-primary btn-block">
            Update
        </a>
                <a type="submit"
                   ng-click="model.uploadImage(model.navigatedUser)"
                   class="btn btn-primary btn-block">
                    Upload
                </a>

        <a ng-click="model.logout()"
           class="btn btn-danger btn-block">
            Logout
        </a>
            </div>
        </form>

        <div class="alert alert-danger" ng-show="model.error">
            
        </div>

        <div class="alert alert-success" ng-show="model.message">
            
        </div>

    </div>

Here is the code for uploadImage function in the controller:

        function uploadImage(user) {
        UserService
            .uploadImage(vm.navigateUserId, user)
            .then(function (response) {
                if (response.data) {
                    $route.reload();
                }
                else {
                    alert("Error updating user information!")
                }
            });
    }

Below is the client side service request from SERVICE.CLIENT. This uses UserService

 function uploadImage(userId, user) {
        return $http.post("/api/project/upload/"+ userId, user);
    }

And lastly Below is my Server side code for uploading Image. in SERVICE.SERVER

 var multer = require('multer');
var upload = multer({ dest: __dirname+'/../../public/uploads' });

    app.post("/api/project/upload/:id",upload.single('myFile'),uploadImage);

    function uploadImage(req, res) {
    var myFile        = req.file;
    var userId        = req.params.id;
    var originalname  = myFile.originalname; // file name on user's computer
    var filename      = myFile.filename;     // new file name in upload folder
    var path          = myFile.path;         // full path of uploaded file
    var destination   = myFile.destination;  // folder where file is saved to
    var size          = myFile.size;
    var mimetype      = myFile.mimetype;
    projectUserModel
        .findUserById(userId)
        .then(function (userData) {
            userData.imgUrl = '/uploads/'+filename;
            userData.save();
            var callbackUrl="/project/#/user/"+userId;
            res.redirect(callbackUrl);
        },function (error) {
            res.sendStatus(404);
            return;
        });
}

Logically I feel like my approach is correct but I just cannot get it to work. I always get undefined for myFile in uploadImage function. It is unable to fetch the file from req.file;

Please help me I am stuck on this for a long time. Thank You in Advance.



via Varun

No comments:

Post a Comment