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

标签 angularjs amazon-web-services amazon-s3 mongoose

我正在通过前端将我的文件发送到 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 = {};
    });
  }
  };

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

那似乎效率不高。

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

示例指南创建者:
    function guid() {
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();
}

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

最佳答案

一个好的 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; };

关于angularjs - 如何设置唯一的 aws S3 文件名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37198038/

相关文章:

node.js - 如何以编程方式将aws凭证和配置传递给nodejs中的aws sdk?

javascript - 跨域请求 对 AWS S3 的 AJAX 请求有时会导致 CORS 错误

c# - PLUpload C# 直接到 S3 工作示例

url - 我的亚马逊 s3 存储桶 URL 是什么?如何将许多文件上传到 s3 存储桶?

javascript - 如何使用 ngresouce 将数据从 angularjs 发送到远程服务器

javascript - 链接函数没有被调用

amazon-web-services - 以 ".aws"开头的文件夹是什么意思?

mysql - MySQL 上的查询缓存会在一段时间后自动重置吗?一些结果缓存了一点,但第二天会重置

javascript - ng-model 外部 Controller

javascript - 在angular js中从web api下载csv文件