如何设置唯一的 aws S3 文件名?
Posted
技术标签:
【中文标题】如何设置唯一的 aws S3 文件名?【英文标题】:how to set a unique aws S3 file name? 【发布时间】:2016-09-08 22:40:02 【问题描述】:我正在通过前端将我的文件发送到一个 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 承诺的更新。
这似乎没有效率。
我可以创建一个 guid 并将其分配给 s3 文件名,并在 distillery 对象上保留对它的引用。不过,这似乎很hacky。
Guid 创建者示例:
function guid()
function s4()
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
实现我想要的最干净的方法是什么?
【问题讨论】:
你可能想研究使用像fineuploader这样的包 【参考方案1】:一个好的 GUID 生成器是解决唯一 ID 问题的一种非常标准的方法。根据算法,名称冲突的可能性可能接近于零。如你所知,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; ;
【讨论】:
它会接近于零吗?假设我有一个像 instagram 这样的应用程序? “为简单起见,假设统一概率,如果截至 2014 年地球上的每个人都拥有 6 亿个 GUID,那么重复的概率约为 50%。”不确定我是否理解这个概率,但它似乎很低。有关更多信息,请参阅 en.wikipedia.org/wiki/Globally_unique_identifier。 所以如果是这样的话,你几乎可以保证有一个副本。由于重复的概率为 50%,因此您应该在 2 个新的 GUID 之后发生冲突。 截至 2014 年,地球上每个人拥有 6 亿个 GUID 的概率达到 50%……每个人。以上是关于如何设置唯一的 aws S3 文件名?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Spring Cloud AWS 从 S3 中删除文件?