我正在尝试在 Cloud Modules Guide之后调整Parse Cloud Code中的图像。
基本思想如下:当在用户上调用afterSave时,检查小配置文件pic是否为空,标准配置文件pic是否为空。如果为true,则从Parse获取标准配置文件pic,读入缓冲区,创建文件,保存文件,然后将文件添加到User并保存。不幸的是,该文件似乎没有正确保存。
这是cloud afterSave函数:
Parse.Cloud.afterSave(Parse.User, function(request) {
...
Parse.Cloud.httpRequest({
url: request.object.get("profilePicture").url(),
success: function(response) {
// The file contents are in response.buffer.
var image = new Image();
console.log("Buffer: " + response.buffer );
console.log("Length " + response.buffer.length);
image.setData(response.buffer);
var imgData = image.data();
// Save the image into a new file.
var base64 = imgData.toString("base64");
var scaled = new Parse.File("thumbnail.png", { base64: base64 });
scaled.save().then(function() {
request.object.set("profilePictureSmall", scaled);
request.object.save();
}, function(error) {
console.log( "The file either could not be read, or could not be saved to Parse.");
});
}
});
...
});
User对象似乎保存得很好,但保存的图像文件是一个损坏的图像。
奇怪的是console.log("Length " + response.buffer.length);
输出适当大小的控制台。
console.log("Buffer: " + response.buffer );
提供输出:�PNG
知道这里发生了什么吗?
答案 0 :(得分:4)
问题是setData()
是一个异步调用,你需要在下一个位之前等待它完成。
http://parse.com/docs/js/symbols/Image.html#setData
这是一个片段:
Parse.Cloud.httpRequest({
url: request.object.get("profilePicture").url()
}).then(function(response) {
var image = new Image();
return image.setData(response.buffer);
}).then(function(image) {
// make it fit in 100x100
var width = 100, height = 100;
if (image.width() > image.height()) {
// work out scaled height
height = image.height() * (100/image.width());
} else {
// work out scaled width
width = image.width() * (100/image.height());
}
console.log("..scale to " + width + "x" + height);
return image.scale({
width: width,
height: height
});
}).then(function(scaledImage) {
// get the image data in a Buffer
return scaledImage.data();
}).then(function(buffer) {
// save the image to a new file
console.log("..saving file");
var base64 = buffer.toString("base64");
var name = "Thumbnail.png";
var thumbnail = new Parse.File(name, { base64: base64 });
return thumbnail.save();
}).then(function(thumbnail) {
// attach the image file to the original object
console.log("..attaching file");
request.object.set("profilePictureSmall", thumbnail);
return request.object.save();
}) /* further chaining here for after-save */;
你基本上必须将你的承诺链接在一起,以便完成上一步。