nodejs将网络图片调用企业微信的上传临时素材API示例
时间: 2023-05-20 17:07:14 浏览: 124
以下是一个使用 Node.js 调用企业微信上传临时素材 API 上传网络图片的示例代码:
```javascript
const https = require('https');
const fs = require('fs');
const path = require('path');
const accessToken = 'your_access_token';
const baseUrl = 'https://qyapi.weixin.qq.com/cgi-bin/';
const imageUrl = 'https://example.com/image.png';
const uploadUrl = baseUrl + 'media/upload?access_token=' + accessToken + '&type=image';
https.get(imageUrl, (res) => {
let data = '';
res.setEncoding('binary');
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
const fileName = path.basename(imageUrl);
const fileData = new Buffer(data, 'binary');
const postData = {
'media': fileData
};
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
}
};
const req = https.request(uploadUrl, requestOptions, (res) => {
let body = '';
res.on('data', (chunk) => {
body += chunk;
});
res.on('end', () => {
const response = JSON.parse(body);
if (response.errcode === 0) {
console.log('上传成功,素材 ID:' + response.media_id);
} else {
console.error('上传失败:' + response.errmsg);
}
});
});
const boundaryKey = Math.random().toString(16);
const boundary = '----' + boundaryKey;
const endBoundary = '\r\n--' + boundary + '--\r\n';
const contentDisposition = 'Content-Disposition: form-data; name="media"; filename="' + fileName + '"\r\n';
const contentType = 'Content-Type: image/png\r\n\r\n';
const payload = '--' + boundary + '\r\n'
+ contentDisposition
+ contentType
+ fileData.toString('binary')
+ endBoundary;
req.write(payload);
req.end();
});
}).on('error', (e) => {
console.error('下载图片时发生错误:' + e.message);
});
```
请将 `your_access_token` 替换为您的企业微信应用的 access_token,`imageUrl` 替换为您的网络图片的 URL。此代码将从指定的 URL 下载图片,并使用 multipart/form-data 格式,将图片文件上传到企业微信的临时素材库中。
阅读全文