Meteor CollectionFS:在显示之前,请确保图像已上传

Meteor CollectionFS: Make sure the image is uploaded before displaying

本文关键字:确保 图像 CollectionFS 显示 Meteor      更新时间:2023-09-26

我正在将CollectionFS包与S3适配器一起使用,我已经研究了一些不同的解决方案,但无法使其正常工作。

问题:即使文件/图像被成功上传到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(){}),但不起作用。

问题是,当原始图像保存在服务器上时,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上,这在您的情况下可能是不正确的。由于用户对象在客户端是被动的,因此此更新将导致配置文件照片自动更新。

我发现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);
     }
   });
});