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 submitte
I had the same problem. I solved it by creating my own models to store meta data and my own upload methods.
I created a model File
which will store info like name,type,url,userId ( same as yours)
I created my own upload remote method because I was unable to do it with the hooks. Container model is the model which is created by loopback-component-storage.
var fileInfo = fileObj.files.myFile[0];
Here myFile is the fieldname for file upload, so you will have to change it accordingly. If you don't specify any field, then it will come as fileObj.file.null[0]
.
This code lacks proper error checking, do it before deploying it in production.
File.uploadFile = function (ctx,options,cb) {
File.app.models.container.upload(ctx.req,ctx.result,options,function (err,fileObj) {
if(err) cb(err);
else{
// Here myFile is the field name associated with upload. You should change it to something else if you
var fileInfo = fileObj.files.myFile[0];
File.create({
name: fileInfo.name,
type: fileInfo.type,
container: fileInfo.container,
userId: ctx.req.accessToken.userId,
url: CONTAINERS_URL+fileInfo.container+'/download/'+fileInfo.name // This is a hack for creating links
},function (err,obj) {
if(err){
console.log('Error in uploading' + err);
cb(err);
}
else{
cb(null,obj);
}
});
}
});
};
File.remoteMethod(
'uploadFile',
{
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'}
}
);