我正在使用 gridfs
将图像存储在 mongoDB
中。当我在后台更新图像并希望在上传完成后在屏幕上更新它们时,我遇到了问题。当我的 mongoDB 中存储有图像文档时,我会触发一个事件,然后更新屏幕。看起来该文档是在上传图像时创建的,因为如果我这样做,我的图像就会因 503 错误
(服务不可用)而损坏。当我刷新页面时,图像出现在屏幕上。
我相信问题是我尝试在图像仍在上传时获取图像。我想做一个 $.get(imagesURL)
并捕获 503 错误,但我不知道该怎么做。如果我能捕获错误,我可以执行一个循环并等待其上传。
也许你们也有更好的解决方案或者知道如何使用 jquery 捕获 503 错误?
我对图像使用普通的文件输入字段
(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)
最佳答案
像这样的东西应该可以工作。该模式是使用响应式(Reactive)数据源设置模板助手 - 在本例中为 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;
}
});
关于javascript - 使用jquery处理503错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31888994/