javascript - 如何使用mean.js上传图像并将其保存到数据库(mongoose)

标签 javascript angularjs meanjs

我是平均堆栈的新手。我想知道如何通过 AngularJS 将图像文件上传到数据库(mongoose)。如果您能给我提供一些代码,请。我在互联网上搜索过,找到了这段代码,但它对我不起作用

HTML 代码:

<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>

客户端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);
    });
};

我的问题是,即使选择文件后, Controller 也不会触发。我还保留了一个控制台来测试,但它不起作用。

最佳答案

这是我对类似问题的回答,它将文件保存在服务器上并将 url/name 放入 mongoDB 中。 https://stackoverflow.com/a/28148042/4494320
它需要 multer (npm install multer --save)。

关于javascript - 如何使用mean.js上传图像并将其保存到数据库(mongoose),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27774227/

相关文章:

javascript - 用户授权不适用于 Mean.JS

javascript - 切换动画播放状态时出现问题

javascript - 计算器 - 第一个计算结果显示,但第二个计算结果不显示

javascript - angularJS - 通过在 div 中单击鼠标获取 x 和 y 位置

javascript - 如何在 angularjs 中 trim ()字符串?

node.js - 你的意思是没有创建应用程序文件夹

angularjs - 具有多个服务器布局的 meanjs 应用程序

javascript - 设置为带有大量 ""的变量文本

javascript - 根据浏览器高度动画div

javascript - <br> ng-repeat angular-js中的标签