Sails.js检查东西上传文件到MongoDB与船长(有效的文件,图像调整大小等) [英] Sails.js checking stuff before uploading files to MongoDB with skipper (valid files, image resizing etc)

查看:262
本文介绍了Sails.js检查东西上传文件到MongoDB与船长(有效的文件,图像调整大小等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个文件上传系统在我的应用程序。我的后端是Sails.js(10.4),它作为我单独的前端(Angular)的API。

我选择将上传的文件存储到我的MongoDB实例中,并使用文件上传模块Skipper中的sails。我正在使用适配器skipper-gridfs( https://github.com/willhuang85/skipper-gridfs)将文件上传到mongo。

现在,上传文件本身并不是问题:我在我的客户端上使用dropzone.js,它发送上传文件到/ api / v1 / files / upload。这些文件将被上传。



为了达到这个目的,我在我的FileController中使用下面的代码:

<$ p上传({$ b $上传文件())。 ..
adapter:require('skipper-gridfs'),
uri:'mongodb:// localhost:27017 / db_name.files'
},function (err,files){
if(err){
return res.serverError(err);
}
console.log('',files);
返回res.json({
message:files.length +'file(s)uploaded successfully!',
files:files
});
});
}
};

现在的问题是:我想在文件上传之前先做些什么。具体来说有两件事:


  1. 检查文件是否被允许:content-type头是否与我想允许的文件类型匹配? (jpeg,png,pdf等 - 只是基本的文件)。
  2. 如果文件是一个图像,使用imagemagick(或类似的东西)将其大小调整为几个预定义的大小。 / li>
  3. 添加也将保存到数据库的特定于文件的信息:对上传文件的用户的引用,以及对该文件的引用(即文章/注释)的一部分。

我不知道从哪里开始或者如何实现这种功能。所以任何帮助将不胜感激!

解决方案

好吧,经过这一段时间的摆弄,我设法找到一种方法这似乎工作。

它可能会更好,但它做我现在要做的:

  upload:function(req,res){
var upload = req.file('file')._ files [0] .stream,
headers = upload.headers,
byteCount = upload.byteCount,
validated = true,
errorMessages = [],
fileParams = {},
settings = {
allowedTypes:['image / jpeg','image / png'],
maxBytes:100 * 1024 * 1024
};
$ b $ //检查文件类型
if(_.indexOf(settings.allowedTypes,headers ['content-type'])=== -1){
validated = false ;
errorMessages.push('错误的文件类型('+ headers ['content-type'] +')。');

//检查文件大小
if(byteCount> settings.maxBytes){
validated = false;
errorMessages.push('Filesize exceeded:'+ byteCount +'/'+ settings.maxBytes +'。');
}

//上传文件。
if(validated){
sails.log.verbose(__ filename +':'+ __line +'[File validated:starting upload。]');
$ b $ //首先上传文件
req.file('file')。upload({},function(err,files){
if(err){
return res.serverError(err);
}

fileParams = {
fileName:files [0] .fd.split('/')。pop() split('。')。shift(),
extension:files [0] .fd.split('。')。pop(),
originalName:upload.filename,
contentType :files [0] .type,
fileSize:files [0] .size,
uploadedBy:req.userID
};

//创建文件模型。
File.create(fileParams,function(err,newFile){
if(err){
return res.serverError(err);
}
return res .json(200,{
message:files.length +'file(s)uploaded successfully!',
file:new文件
});
});
});
} else {
sails.log.verbose(__ filename +':'+ __line +'[File not uploaded:',errorMessages.join(' - ')+']');

return res.json(400,{
message:'File not uploaded:'+ errorMessages.join(' - ')
});





而不是使用skipper-gridfs我选择使用本地文件存储,但这个想法保持不变。再次,它不是完整的,但它是一个简单的方法来验证简单的东西,如文件类型和大小。如果有人有更好的解决方案,请发布:)!

I'm currently creating a file upload system in my application. My backend is Sails.js (10.4), which serves as an API for my separate front-end (Angular).

I've chosen to store the files I'm uploading to my MongoDB instance, and using sails' build in file upload module Skipper. I'm using the adapter skipper-gridfs (https://github.com/willhuang85/skipper-gridfs) to upload the files to mongo.

Now, it's not a problem to upload the files themselves: I'm using dropzone.js on my client, which sends the uploaded files to /api/v1/files/upload. The files will get uploaded.

To achieve this i'm using the following code in my FileController:

module.exports = {
    upload: function(req, res) {
        req.file('uploadfile').upload({
            // ...any other options here...
            adapter: require('skipper-gridfs'),
            uri: 'mongodb://localhost:27017/db_name.files'
        }, function(err, files) {
            if (err) {
                return res.serverError(err);
            }
            console.log('', files);
            return res.json({
                message: files.length + ' file(s) uploaded successfully!',
                files: files
            });
        });
    }
};

Now the problem: I want to do stuff with the files before they get uploaded. Specifically two things:

  1. Check if the file is allowed: does the content-type header match the file types I want to allow? (jpeg, png, pdf etc. - just basic files).
  2. If the file is an image, resize it to a few pre-defined sizes using imagemagick (or something similar).
  3. Add file-specific information that will also be saved to the database: a reference to the user who has uploaded the file, and a reference to the model (i.e. article/comment) the file is part of.

I don't have a clue where to start or how to implement this kind of functionality. So any help would be greatly appreciated!

解决方案

Ok, after fiddling with this for a while I've managed to find a way that seems to work.

It could probably be better, but it does what I want it to do for now:

upload: function(req, res) {
    var upload = req.file('file')._files[0].stream,
        headers = upload.headers,
        byteCount = upload.byteCount,
        validated = true,
        errorMessages = [],
        fileParams = {},
        settings = {
            allowedTypes: ['image/jpeg', 'image/png'],
            maxBytes: 100 * 1024 * 1024
        };

    // Check file type
    if (_.indexOf(settings.allowedTypes, headers['content-type']) === -1) {
        validated = false;
        errorMessages.push('Wrong filetype (' + headers['content-type'] + ').');
    }
    // Check file size
    if (byteCount > settings.maxBytes) {
        validated = false;
        errorMessages.push('Filesize exceeded: ' + byteCount + '/' + settings.maxBytes + '.');
    }

    // Upload the file.
    if (validated) {
        sails.log.verbose(__filename + ':' + __line + ' [File validated: starting upload.]');

        // First upload the file
        req.file('file').upload({}, function(err, files) {
            if (err) {
                return res.serverError(err);
            }

            fileParams = {
                fileName: files[0].fd.split('/').pop().split('.').shift(),
                extension: files[0].fd.split('.').pop(),
                originalName: upload.filename,
                contentType: files[0].type,
                fileSize: files[0].size,
                uploadedBy: req.userID
            };

            // Create a File model.
            File.create(fileParams, function(err, newFile) {
                if (err) {
                    return res.serverError(err);
                }
                return res.json(200, {
                    message: files.length + ' file(s) uploaded successfully!',
                    file: newFile
                });
            });
        });
    } else {
        sails.log.verbose(__filename + ':' + __line + ' [File not uploaded: ', errorMessages.join(' - ') + ']');

        return res.json(400, {
            message: 'File not uploaded: ' + errorMessages.join(' - ')
        });
    }

},

Instead of using skipper-gridfs i've chosen to use local file storage, but the idea stays the same. Again, it's not as complete as it should be yet, but it's an easy way to validate simple stuff like filetype and size. If somebody has a better solution, please post it :)!

这篇关于Sails.js检查东西上传文件到MongoDB与船长(有效的文件,图像调整大小等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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