2015-08-08 110 views
0

我使用gridfs存儲圖像在mongoDB。當我在後臺更新圖像並想要在完成上傳時在屏幕上更新它們時遇到問題。當我將一個圖像文件存儲在我的mongoDB中然後更新屏幕時,我會發起一個事件。它看起來像上傳圖像時創建的文檔,因爲如果我這樣做,我的圖像打破了503 error(服務不可用)。當我刷新頁面時,圖像出現在屏幕上。處理503錯誤與jquery

我相信問題在於我在嘗試獲取圖片時仍然上傳。我想做一個$.get(imagesURL)並捕獲503錯誤,但我不知道如何做到這一點。如果我可以捕捉到錯誤,我可以做一個循環,並等待其上傳。

也許你們也有更好的解決方案或知道如何使用jquery捕捉503錯誤? 我用正常file input field的圖像

(在meteorjs我的模板事件的一部分)

'change #avatarForm': function (event) { 
     FS.Utility.eachFile(event, function (file) { 
      Images.insert(file, function (err, fileObj) { 
       if (err) { 
        // handle error 
       } else { 
        // handle success depending what you need to do 
        var userId = Meteor.userId(); 
        var imagesURL = { 
         "profile.image": "/cfs/files/images/" + fileObj._id 
        }; 
        Meteor.users.update(userId, {$set: imagesURL}); 

        function checkAvatar() { 
         $.get(imagesURL) 
          .complete(function() { 
           Session.set("registerAvatar", "/cfs/files/images/" + fileObj._id); 
          }).onerror(function() { 
           console.log("but still uploading"); 
           checkAvatar(); 
          }); 
         console.log("image saved!"); 
        } 
        checkAvatar(); 
       } 
      }); 
     }); 
    }, 

我的代碼應該只火屏幕上的新圖像(URL設置爲SessionVar)當圖像已完成但尚未運作。

這是我確切的錯誤

Failed to load resource: the server responded with a status of 503 (Service Unavailable) 

回答

0

這樣的事情應該工作。該模式是設置一個模板助手與反應數據源 - 在這種情況下,Meteor.user()。當Meteor.user()發生變化時,模板助手將渲染出新數據,而無需手動提取任何數據:

<template name="test"> 

    <div>Profile Image:</div> 
    {{#if profileImage}} 
    <div><img src="{{profileImage}}"></div> 
    {{/if}} 

</template> 

Template.test.events({ 

    'change #avatarForm': function(event) { 
    FS.Utility.eachFile(event, function(file) { 
     Images.insert(file, function(err, fileObj) { 
     if (err) { 
      // handle error 
     } else { 
      // handle success depending what you need to do 
      var userId = Meteor.userId(); 
      var profileImage = { 
      "profile.image.url": fileObj.url(), 
      "profile.image.id": fileObj._id 
      }; 
      Meteor.users.update(userId, { 
      $set: profileImage 
      }); 
     } 
     }); 
    }); 
    }, 

}); 

Template.test.helpers({ 
    profileImage: function() { 
    return Meteor.user().profile.image.url; 
    } 
});