如何设置唯一的 aws S3 文件名?

Noo*_*ter 3 amazon-s3 mongoose amazon-web-services angularjs

我正在通过前端将我的文件发送到 s3 存储桶,因为从我读过的内容来看,这似乎更有效。

但是,对于我的一些模式/集合,我不会有与文件/照片相关联的 ID——因为它们是在上传的同时创建的:

  $scope.add = function(){

  if($scope.file.photo){
      $scope.distiller.photo = 'http://s3.amazonaws.com/whiskey-upload/distillers/' 
      + ' needs to be assigned to guid or collection id'
        Distillery.create($scope.distiller).then(function(res){
          console.log(res);
          $scope.distillers.push(res.data.distiller);
      var files = $scope.file;
      var filename = files.photo.$ngfName;
      var type = files.type;
      var folder = 'distillers/';

      var query = {
          files: files,
          folder: folder,
          filename: res.data.distiller._id,
          type: type
        };

        Uploads.awsUpload(query).then(function(){
          $scope.distiller = {};
          $scope.file = {};
        });
    });
  }
  else{
    Distillery.create($scope.distiller).then(function(res){
      toastr.success('distillery created without photo');
      $scope.distiller = {};
    });
  }
  };
Run Code Online (Sandbox Code Playgroud)

上面的代码不起作用,除非我在创建 distillery 对象并且将文件上传到 s3 之后发送了关于 aws.Upload 承诺的更新。

那似乎效率不高。

我可以创建一个 guid 并将其分配给 s3 文件名,并在 distillery 对象上保留该文件名的引用。不过,这似乎很hacky。

示例指南创建者:

    function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}
Run Code Online (Sandbox Code Playgroud)

实现我想要的最干净的方法是什么?

Rod*_*o M 5

一个好的 GUID 生成器是解决唯一 ID 问题的非常标准的方法。根据算法的不同,名称冲突的可能性可能接近于零。如您所知,JavaScript 没有原生的,因此像您这样的 JavaScript 是合理的。我不认为它是hacky。

这是@briguy37 的另一个:

function generateUUID() {
     var d = new Date().getTime();
     var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
         var r = (d + Math.random()*16)%16 | 0;
         d = Math.floor(d/16);
        return (c=='x' ? r : (r&0x3|0x8)).toString(16);
     });
     return uuid; };
Run Code Online (Sandbox Code Playgroud)