What I want to do: Have an html form, with a file input inside. When a file is chosen, the file input should upload the file, and get a file id, so when the form is submitted, the file id is posted with the form and written in the database.
Shorter version: I want to store meta data (id for example) with my files.
Sounds simple, yet I struggle to do that in LoopBack.
There has been a couple conversations ( 1, 2 ) about this topic, and neither seemed to lead to a solution, so I thought this might be a good place to find one once and for all.
The simplest solution would be to use model relations, but LoopBack doesn't support relations with the file storage service. Bump. So we have to go with a persistedmodel named File
for example, and override default create, delete so it saves and deletes from the file store model I have - named Storage
.
My setup so far:
- I have a model /api/Storage which is connected to a loopback storage service and is saving file successfully to the local filesystem.
- I have a PersistedModel connected to Mongo with file meta data:
name
,size
,url
andobjectId
- I have a remote hook set up before
create
so the file can be saved first and then it'surl
can be injected intoFile.create()
I'm there, and according to this LoopBack page, I have the ctx which should have the file inside:
File.beforeRemote('create', function(ctx, affectedModelInstance, next) {})`
What's ctx
?
ctx.req
: Express Request object.
ctx.result
: Express Response object.
Ok, so now I'm at the Express page, pretty lost, and it sais something about a 'body-parsing middleware' which I have no idea what it might be.
I feel like I'm close to the solution, any help would be appreciated. Is this approach right?
File.beforeRemote('upload', function(ctx, modelInstance, next){ console.log(ctx.req); next(); });
, however I can't see any file related information in the ctx object, and the modelInstance isundefined
too... Worth noting that myFile
here is the model with the storage service datasource. – ClearsightedFile
and notStorage
models. – VitrainStorage.afterRemote('upload',function(ctx, modelInstance, next){ console.log('create file',modelInstance.result.files.file); next(); });
– Vitrain