如何使用均值js将图像文件上传到mongoose数据库 [英] How do you upload an image file to mongoose database using mean js

查看:110
本文介绍了如何使用均值js将图像文件上传到mongoose数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的平均堆栈。我想知道如何通过angularjs将图像文件上传到数据库(mongoose)。如有可能,请提供一些代码。我搜索过互联网,但我没有找到任何合适的代码。

解决方案

你有很多方法和工具来实现你想。我把其中一个放在这里:



对于这一个,我使用有角度-file-upload 作为客户端。所以你需要这个控制器:

  $ scope.onFileSelect = function(image){
if .isArray(image)){
image = image [0];
}

//这是我如何处理客户端的文件类型
if(image.type!=='image / png'&&& image.type! =='image / jpeg'){
alert('只接受PNG和JPEG');
返回;
}

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

$ scope.upload = $ upload.upload({
url:'/ upload / image',
方法:'POST',
文件:image
})。progress(function(event){
$ scope.uploadProgress = Math.floor(event.loaded / event.total);
$ scope。$ apply();
})。success(function(data,status,headers,config){
$ scope.uploadInProgress = false;
//如果您需要立即上传文件
$ scope.uploadedImage = JSON .parse(data);
})。error(function(err){
$ scope.uploadInProgress = false;
console.log('Error uploading file:'+ err.message | | err);
});
};

您的视图中的以下代码(我还为现代浏览器添加了文件类型处理程序):

 上传图片< input type =filedata-ng-file-select =onFileSelect($ files)accept =image / png,image / jpeg> 
< span data-ng-if =uploadInProgress>上传进度:{{uploadProgress}}< / span>
< img data-ng-src =uploadedImagedata-ng-if =uploadedImage>

对于服务器端,我使用了节点多方



这是您在服务器端路由中需要的:

  app.route('/ upload / image')
.post(upload.postImage);

在服务器端控制器中:

  var uuid = require('node-uuid'),
multiparty = require('multiparty'),
fs = require('fs');

exports.postImage = function(req,res){
var form = new multiparty.Form();
form.parse(req,function(err,fields,files){
var file = files.file [0];
var contentType = file.headers ['content-type'] ;
var tmpPath = file.path;
var extIndex = tmpPath.lastIndexOf('。');
var extension =(extIndex< 0)?'':tmpPath.substr(extIndex );
// uuid用于生成唯一的文件名
var fileName = uuid.v4()+ extension;
var destPath ='path / to / where / you / want / to / store / your / files /'+ fileName;

//服务器端文件类型检查器
if(contentType!=='image / png'&& contentType!==' image / jpeg'){
fs.unlink(tmpPath);
return res.status(400).send('不支持的文件类型');
}

fs.rename(tmpPath,destPath,function(err){
if(err){
return res.status(400).send('Image is not saved:');
}
return res.json(destPath);
});
});
};

如您所见,我将上传的文件存储在文件系统中,所以我只是使用node-uuid 给他们独一无二的名字。如果要将文件直接存储在数据库中,则不需要uuid,在这种情况下,只需使用缓冲区数据类型。
另外请注意加注 angularFileUpload 到您的角度模块依赖项。


I am new to the mean stack. I want to know how to upload an image file to the database(mongoose) through angularjs. If possible, please provide me with some code. I have searched the internet but I haven't found any suitable code.

解决方案

You have plenty ways and tools to achieve what you want. I put one of them here:

For this one I use angular-file-upload as client side. So you need this one in your controller:

        $scope.onFileSelect = function(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);
            });
        };

And following code in your view (I also added file type handler for modern browsers):

Upload image <input type="file" data-ng-file-select="onFileSelect($files)" accept="image/png, image/jpeg">
<span data-ng-if="uploadInProgress">Upload progress: {{ uploadProgress }}</span>
<img data-ng-src="uploadedImage" data-ng-if="uploadedImage">

For server side, I used node-multiparty.

And this is what you need in your server side route:

app.route('/upload/image')
    .post(upload.postImage);

And in server side controller:

var uuid = require('node-uuid'),
    multiparty = require('multiparty'),
    fs = require('fs');

exports.postImage = function(req, res) {
    var form = new multiparty.Form();
    form.parse(req, function(err, fields, files) {
        var file = files.file[0];
        var contentType = file.headers['content-type'];
        var tmpPath = file.path;
        var extIndex = tmpPath.lastIndexOf('.');
        var extension = (extIndex < 0) ? '' : tmpPath.substr(extIndex);
        // uuid is for generating unique filenames. 
        var fileName = uuid.v4() + extension;
        var destPath = 'path/to/where/you/want/to/store/your/files/' + fileName;

        // Server side file type checker.
        if (contentType !== 'image/png' && contentType !== 'image/jpeg') {
            fs.unlink(tmpPath);
            return res.status(400).send('Unsupported file type.');
        }

        fs.rename(tmpPath, destPath, function(err) {
            if (err) {
                return res.status(400).send('Image is not saved:');
            }
            return res.json(destPath);
        });
    });
};

As you can see, I store uploaded files in file system, so I just used node-uuid to give them unique name. If you want to store your files directly in database, you don't need uuid, and in that case, just use Buffer data type. Also please take care of things like adding angularFileUpload to your angular module dependencies.

这篇关于如何使用均值js将图像文件上传到mongoose数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆