Dar*_*tra 4 file-upload mongodb gridfs sails.js skipper
我目前正在我的应用程序中创建一个文件上传系统.我的后端是Sails.js(10.4),它作为我单独的前端(Angular)的API.
我选择将我上传的文件存储到我的MongoDB实例,并使用sails的内置文件上传模块Skipper.我正在使用适配器skipper-gridfs(https://github.com/willhuang85/skipper-gridfs)将文件上传到mongo.
现在,上传文件本身不是问题:我在我的客户端上使用dropzone.js,它将上传的文件发送到/ api/v1/files/upload.文件将上传.
为了实现这一点,我在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
});
});
}
};
Run Code Online (Sandbox Code Playgroud)
现在问题是:我想在上传文件之前先处理这些文件.特别是两件事:
我不知道从哪里开始或如何实现这种功能.所以任何帮助将不胜感激!
Dar*_*tra 10
好吧,在摆弄了一段时间之后,我已经设法找到一种似乎有效的方法.
它可能会更好,但它做了我想要它现在做的事情:
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(' - ')
});
}
},
Run Code Online (Sandbox Code Playgroud)
我选择使用本地文件存储,而不是使用skipper-gridfs,但这个想法保持不变.同样,它并不像它应该的那样完整,但它是一种简单的方法来验证文件类型和大小等简单的东西.如果有人有更好的解决方案,请发布:)!
| 归档时间: |
|
| 查看次数: |
3277 次 |
| 最近记录: |