我正在使用带有S3适配器的CollectionFS软件包,我已经看了几个不同的解决方案,但无法使其正常工作。
问题:即使文件/图像成功上传到S3,也会在安全显示图像之前触发成功上传的回调。这会导致有时显示损坏的图像。
我发现了fileObj.once("uploaded", function(){})
回调,但似乎"已上传"基本上是指将图像发送到服务器。那时S3上传不会发生。我发现的一个临时解决方法就是让setTimeout
持续3-4秒,但这不可靠。
这是我的上传代码:
FS.Utility.eachFile(event, function(file) {
Session.set('profilePhotoUploaded', false);
var newFile = new FS.File(file);
newFile.metadata = {owner: Meteor.userId()};
ProfileImages.insert(newFile, function (err, fileObj) {
if (err){
console.log("error! - " + err);
} else {
// handle success depending what you need to do
var userId = Meteor.userId();
// This does NOT run when image is stored in S3. I think it runs when the image reached the app server.
fileObj.once("uploaded", function () {
// timeout of 3 seconds to make sure image is ready to be displayed
// --- This is not a good solution and it image does is not always ready
setTimeout(function(){
var uploadedImage = {
"profile.image.url": "/cfs/files/profileImages/" + fileObj._id
};
Meteor.users.update(userId, {$set: uploadedImage});
Session.set('profilePhotoUploaded', true);
}, 3000);
console.log("Done uploading!");
});
}
});
});
是否有不同的回调来检查图像是否实际存储在S3中?我试过了fileObj.once("stored", function(){})
,但这不起作用。
答案 0 :(得分:2)
问题是当原始图像保存在服务器上时会触发stored
挂钩,因此如果您要创建多个副本(缩略图),则会在存储缩略图之前触发此挂钩。您可以通过检查storeName参数来检查存储的缩略图版本。在服务器端文件中,您定义ProfileImages
集合,添加以下代码,将'profilePhotoLarge'
替换为分配给FS.Store.S3
商店的名称:
ProfileImages.on('stored', Meteor.bindEnvironment(function(fileObj, storeName) {
if (storeName === 'profilePhotoLarge') {
Meteor.users.update({_id: fileObj.metadata.owner}, {
$set: {
'profile.image.url': 'https://your AWS region domain/your bucket name/your folder path/' + fileObj._id + '-' +fileObj.name()
}
});
}
}, function() { console.log('Failed to bind environment'); }));
对于个人资料照片,我创建了一个S3存储桶,并设置了允许任何人读取文件的权限,因此我将URL存储到S3上的图像,这在您的情况下可能不正确。由于用户对象在客户端是被动的,因此此更新将导致配置文件照片自动更新。
答案 1 :(得分:1)
我发现fileObj.hasStored("profileImages")
确切地指定了图像存储在S3上的确切时间。因此,在开始上传过程后,我每隔1秒钟启动一个计时器,检查它是否已保存。这可能不是最好的解决方案,但这对我有用。
FS.Utility.eachFile(event, function(file) {
Session.set('profilePhotoUploaded', false);
var newFile = new FS.File(file);
newFile.metadata = {owner: Meteor.userId()}; // TODO: check in deny that id is of the same user
ProfileImages.insert(newFile, function (err, fileObj) {
if (err){
console.log("error! - " + err);
} else {
// handle success depending what you need to do
var userId = Meteor.userId();
// Timer every 1 second
var intervalHandle = Meteor.setInterval(function () {
console.log("Inside interval");
if (fileObj.hasStored("profileImages")) {
// File has been uploaded and stored. Can safely display it on the page.
var uploadedImage = {
"profile.image.url": "/cfs/files/profileImages/" + fileObj._id
};
Meteor.users.update(userId, {$set: uploadedImage});
Session.set('profilePhotoUploaded', true);
// file has stored, close out interval
Meteor.clearInterval(intervalHandle);
}
}, 1000);
}
});
});