将图像编码为URL参数node.js
将图像编码为URL参数node.js
我试图将信息发送到一个外部API。引用他们的支持文档的说法是:“文件应该以Base64编码,并插入到图片参数中。”但是当我尝试这样做时,我得到了一个414-URI过长的错误。\n我写了一个简短的node.js脚本来实现这个目标:\n
var fs = require('fs'); var request = require('request'); var host = "api.xxxxx.com"; var app_id = "xxxxxxxx"; var app_key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; var sessionID = null; function base64_encode(filename) { // 读取二进制数据 var data = fs.readFileSync('./images/' + filename); // 将二进制数据转换为Base64编码的字符串 return new Buffer(data).toString('base64'); } function start() { fs.readdir('./images/', function(err, files) { if (err) { console.log("fs.readdir出错: ", err); } else { files.forEach(function(file) { var base = base64_encode(file); request.post({ url: 'https://api.xxxxxxx.com/media?source=' + base, headers: { 'app_id': app_id, 'app_key': app_key } }, function (error, response, body) { if (response) { console.log('状态:', response.statusCode); console.log('头信息:', JSON.stringify(response.headers)); console.log('响应:', body); } else { console.log("没有响应。"); } }); }); } }); } start();
\n我还尝试将编码后的图片放在form: {}和qs: {}中,并将其移动到了各个位置-但我要么得到一个“缺少必需的源参数”错误,要么如果我看起来做得正确,我得到了414错误。有关以这种方式发送图像的建议吗?这是一个144KB的图像。\n编辑:\n我将代码的主要部分更改为以下内容:\n
files.forEach(function(file) { var data = base64_encode(file); var options = { host: host, port: 443, path: '/media', method: 'POST', headers: { 'app_id': app_id, 'app_key': app_key, 'Content-Type': 'image/jpg', 'Content-Length': data.length } }; var req = https.request(options, function(res) { res.setEncoding('utf8'); res.on('data', function (chunk) { console.log("body: " + chunk); }); }); req.write(data); req.end(); });
\n但是我仍然得到了“缺少必需的源参数”的响应。如何将其指定为“source”参数?
问题的原因是API的文档不够清晰,没有明确说明如何将图像编码为URL参数。解决方法是将图像放在POST请求的参数中,通过HTTP发送数据。以下是使用node.js进行此操作的示例代码:
const axios = require('axios'); const imageUrl = 'https://example.com/image.jpg'; // 图像的URL const apiKey = 'your_api_key'; // API密钥 const params = new URLSearchParams(); params.append('source', imageUrl); axios.post('https://www.kairos.com/docs/api/#emotion-analysis', params, { headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'app_id': 'your_app_id', 'app_key': apiKey } }) .then(response => { console.log(response.data); }) .catch(error => { console.error(error); });
通过将图像URL添加到POST请求的参数中,使用axios库发送请求。在请求头中,设置Content-Type为application/x-www-form-urlencoded,并添加app_id和app_key作为身份验证。
这样,就可以将图像编码为URL参数,并通过POST请求发送给API。请注意,您需要将"your_api_key"和"your_app_id"替换为实际的API密钥和应用程序ID。
希望这可以解决您的问题。如果您有任何疑问,请随时提问。