从 loopback-component-storage 验证和重命名图像文件

Validate and Rename Image file from loopback-component-storage

我收到了与类似的问题,但答案并不令我满意。

使用相同的示例:

At client side

Upload.upload(
{
    url: '/api/containers/container_name/upload',
    file: file,
    fileName: "demoImage.jpg",
    //Additional data with file
    params:{
     username : username
    }
});

要求如下:

  1. 验证文件的文件类型
  2. 修改保存在服务器中的名称
  3. 如果文件或用户名无效则拒绝

这是我使用和遇到的一些参考:

这是我验证文件类型和修改文件名所做的,

datasources.local.js [容器名称是 container]

module.exports = {
  container: {
    root: './upload',
    acl: 'public-read',
    allowedContentTypes: ['image/jpg', 'image/jpeg', 'image/png', 'image/tiff'],
    maxFileSize: 10 * 1024 * 1024,
    getFilename: function(fileInfo) {
      var fileName = fileInfo.name.replace(/\s+/g, '-').toLowerCase();
      return 'image-' + new Date().getTime() + '-' + fileName;
    }
  }
};

拒绝请求应通过 ACL 进行身份验证和授权检查。基于文件名的拒绝可以通过远程挂钩来完成。

下面是一个示例(我没有测试这个)

Container.beforeRemote('create', function(context, comment, next) {
  if (context.req.body.fileName.length < 7) {
    context.res.statusCode = 401;
    next(new Error('Filename is too short!'));
  } else {
    next();
  }
});

我希望这可以帮助你找到你想要的方式。