以下是使用loopback存储文件元数据的完整解决方案。
你需要一个容器模型。
common/models/container.json
{
"name": "container",
"base": "Model",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}
在
server/datasources.json
中创建您的容器数据源。例如:
...
"storage": {
"name": "storage",
"connector": "loopback-component-storage",
"provider": "filesystem",
"root": "/var/www/storage",
"maxFileSize": "52428800"
}
...
你需要在 server/model-config.json
中设置该模型的数据源为你所拥有的 loopback-component-storage
:
...
"container": {
"dataSource": "storage",
"public": true
}
...
您还需要一个文件模型来存储元数据并处理容器调用:
common/models/files.json
{
"name": "files",
"base": "PersistedModel",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string"
},
"type": {
"type": "string"
},
"url": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}
现在将文件
与容器
连接起来:
common/models/files.js
var CONTAINERS_URL = '/api/containers/';
module.exports = function(Files) {
Files.upload = function (ctx,options,cb) {
if(!options) options = {};
ctx.req.params.container = 'common';
Files.app.models.container.upload(ctx.req,ctx.result,options,function (err,fileObj) {
if(err) {
cb(err);
} else {
var fileInfo = fileObj.files.file[0];
Files.create({
name: fileInfo.name,
type: fileInfo.type,
container: fileInfo.container,
url: CONTAINERS_URL+fileInfo.container+'/download/'+fileInfo.name
},function (err,obj) {
if (err !== null) {
cb(err);
} else {
cb(null, obj);
}
});
}
});
};
Files.remoteMethod(
'upload',
{
description: 'Uploads a file',
accepts: [
{ arg: 'ctx', type: 'object', http: { source:'context' } },
{ arg: 'options', type: 'object', http:{ source: 'query'} }
],
returns: {
arg: 'fileObject', type: 'object', root: true
},
http: {verb: 'post'}
}
);
};
为了公开文件API,请在model-config.json
文件中添加files
模型,并记得选择正确的数据源:
...
"files": {
"dataSource": "db",
"public": true
}
...
完成! 现在您可以调用POST /api/files/upload
,在file
表单字段中传递文件二进制数据。您将收到id、name、type和url的返回值。
File.beforeRemote('upload', function(ctx, modelInstance, next){ console.log(ctx.req); next(); });
的数据,但是在 ctx 对象中看不到任何与文件相关的信息,而且 modelInstance 也是未定义的... 值得注意的是,这里的File
是具有存储服务数据源的模型。 - RYFNFile
模型而不是Storage
模型的解决方案。 - Mihaly KRStorage.afterRemote('upload',function(ctx, modelInstance, next){ console.log('create file',modelInstance.result.files.file); next(); });
- Mihaly KR