本文介紹Image Search服務Node.js SDK的使用方法及樣本。
準備工作
- 在安裝和使用阿里雲SDK前,確保您已經註冊阿里雲帳號並產生存取金鑰(AccessKey)。詳情請參見t1938336.html#task968。
- 安裝Node.js SDK核心庫。阿里雲Node.js SDK支援的版本為8.0及以上,您可以通過以下方式安裝Node.js SDK:
npm install @alicloud/pop-core -S
- 您也可以使用cnpm、yarn等包管理工具來安裝@alicloud/pop-core。
- 安裝Image SearchNode.js SDK。
npm install @alicloud/imagesearch-2019-03-25 --save
程式碼範例
Node.js完整程式碼範例如下。
'use strict';
const fs = require('fs');
const qs = require("querystring");
const Client = require("@alicloud/imagesearch-2019-03-25");
const client = new Client({
accessKeyId: "<your-access-key-id>",
accessKeySecret: "<your-access-key-secret>",
endpoint: "http://imagesearch.<region>.aliyuncs.com"
});
const options = {
method: 'POST',
"Content-Type": 'application/x-www-form-urlencoded; charset=UTF-8'
};
var picContent = fs.readFileSync("/home/admin/demo.jpg").toString("base64");
async function demo() {
// 添加圖片
const addRequest = {
InstanceName: "demo",
ProductId: "test",
PicName: "test",
PicContent: picContent
};
const addData = qs.stringify(addRequest);
const addResponse = await client.addImage(addData, options);
console.log(1, addResponse);
// 查詢圖片
const searchRequest = {
InstanceName: "test",
PicContent: picContent
};
const searchData = qs.stringify(searchRequest);
const searchResponse = await client.searchImage(searchData, options);
console.log(2, searchResponse);
// 刪除圖片
const deleteRequest = {
InstanceName: "demo",
ProductId: "test"
};
const deleteData = qs.stringify(deleteRequest);
const deleteResponse = await client.deleteImage(deleteData, options);
console.log(3, deleteResponse);
}
demo();