How to store files with meta data in LoopBack?

前端 未结 7 1709
别跟我提以往
别跟我提以往 2020-11-28 03:05

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

相关标签:
7条回答
  • 2020-11-28 04:02

    I had the same problem. I solved it by creating my own models to store meta data and my own upload methods.

    1. I created a model File which will store info like name,type,url,userId ( same as yours)

    2. 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.

    3. 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'}
        }
      
      );
      
    0 讨论(0)
提交回复
热议问题