简体   繁体   中英

How to upload an image and save it to database(mongoose) using mean.js

I am new to the mean stack. I want to know how to upload an image file to the database(mongoose) through AngularJS. Please if you can provide me with some code. I have searched the internet and I have found this code but it was not working to me

HTML code:

<div class="col-md-4 col-xs-8">
    <div class="fileinput fileinput-new" data-provides="fileinput">
        <img class="profile-pic thumbnail" style="width: 200px; height: 150px;" />
        <div>
            <span class="btn btn-default btn-file">
            <span class="fileinput-new upload-button"><span class="glyphicon glyphicon-upload"></span> Upload New Pic</span>
            <input class="file-upload" type="file" data-ng-file-select="onFileSelect($files)"  accept="image/png, image/jpeg" >
            </span>                 
        </div>

        <span data-ng-if="uploadInProgress">Upload progress: {{ uploadProgress }}</span>
        <img data-ng-src="uploadedImage" data-ng-if="uploadedImage">
        <br>
    </div>
</div>

clientside controller.js:

$scope.onFileSelect = function(image) {
    console.log("image selected" + image);
    if (angular.isArray(image)) {
        image = image[0];
    }

    // This is how I handle file types in client side
    if (image.type !== 'image/png' && image.type !== 'image/jpeg') {
        alert('Only PNG and JPEG are accepted.');
        return;
    }

    $scope.uploadInProgress = true;
    $scope.uploadProgress = 0;

    $scope.upload = $upload.upload({
        url: '/upload/image',
        method: 'POST',
        file: image
    }).progress(function(event) {
        $scope.uploadProgress = Math.floor(event.loaded / event.total);
        $scope.$apply();
    }).success(function(data, status, headers, config) {
        $scope.uploadInProgress = false;
        // If you need uploaded file immediately 
        $scope.uploadedImage = JSON.parse(data);      
    }).error(function(err) {
        $scope.uploadInProgress = false;
        console.log('Error uploading file: ' + err.message || err);
    });
};

My problem is even after selecting a file the controller is not triggering. I also kept a console to test but it was not working.

This is my response to similar question, which saves the file on the server and put url/name in mongoDB. https://stackoverflow.com/a/28148042/4494320
It requires multer (npm install multer --save).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM