本文介绍图像搜索服务Node.js SDK的使用方法及示例。

准备工作

  • 在安装和使用阿里云SDK前,确保您已经注册阿里云账号并生成访问密钥(AccessKey)。详情请参见创建AccessKey
  • 安装Node.js SDK核心库。阿里云Node.js SDK支持的版本为8.0及以上,您可以通过以下方式安装Node.js SDK:
    npm install @alicloud/pop-core -S
  • 您也可以使用cnpm、yarn等包管理工具来安装@alicloud/pop-core。
  • 安装图像搜索Node.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();