我正在寻找一种解决方案,可以为特定的图像提供URL,然后使用Javascript检索该图像的数据。我已经发现我不能直接通过文件,所以字节数组或base64可以吗?
具体来说,在有人否决这个问题之前:我想解析URL,并以任何形式将图像发送到我的服务器。有很多类似的问题,但没有一个能回答这个问题。
我需要它干什么?我可以访问API,那里也为我提供了图像url,但我希望它们通过Parse.com服务中的Background Job
上传到我的服务器(类似于CRON作业)。我知道如何将文件与ParseObject
链接,但找不到如何将图像直接下载到ParseCloud
并链接的解决方案。
var Image = require("parse-image");
Parse.Cloud.job("getImagesJob", function(request, status) {
Parse.Cloud.useMasterKey();
var beerObj = Parse.Object.extend("My_class");
var query = new Parse.Query(beerObj);
query.first().then(function(objs) {
var brew = objs.get("brewery");
var bname = objs.get("beer_name");
//var fullName = brew + " " + bname;
var fullName = "Browar Name";
console.log(fullName);
return Parse.Cloud.httpRequest({
method: 'GET',
url: 'api server address',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
params: {
q : fullName,
client_id : '...',
client_secret : '...'
}
}).then(function(httpResponse) {
var json = JSON.parse(httpResponse.text);
if(json.meta.code === 200){
if(json.response.beers.count > 0){
if(json.response.beers.items[0].beer.beer_label === "/default.png"){
console.log("brak etykiety dla " + fullName);
} else {
console.log("znaleziono etykietę dla " + fullName);
Parse.Cloud.httpRequest({ //NOT REACHING
url: json.response.beers.items[0].beer.beer_label,
success: function(response) {
// The file contents are in response.buffer.
var image = new Image();
return image.setData(response.buffer, {
success: function() {
objs.set("logo", image.data());
console.log("udalo sie dolaczyc");
},
error: function(error) {
// The image data was invalid.
console.error(error);
}
})
},
error: function(error) {
// The networking request failed.
}
});
}
} else {
// daj cokolwiek żeby się nie zacięło na jednym
console.log("Brak danych dla piwa: " + fullName);
}
}
}, function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status + httpResponse.text);
});
}).then(function(obj) {
status.success("Zrobione");
}, function(error) {
status.error(error);
});
});
您可以在云代码中使用parse-image
模块,就像在他们的文档中一样
var Image = require("parse-image");
Parse.Cloud.httpRequest({
url: YOUR_URL,
success: function(response) {
// The file contents are in response.buffer.
var image = new Image();
return image.setData(response.buffer, {
success: function() {
console.log("Image is " + image.width() + "x" + image.height() + ".");
},
error: function(error) {
// The image data was invalid.
}
})
},
error: function(error) {
// The networking request failed.
}
});
使用以上代码,您可以使用image.data()
在Buffer中获取图像数据。要获取base64数据,请使用image.data().toString("base64")