我有以下示例代码,要将图像发送到API。
const axios = require('axios');
var image = 'some/image/url/example.png';
axios.post('some/api/url', {
title: 'The quick brown fox',
image: image
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
不幸的是,API不接受基于位图,二进制,base64或字符串的图像。我想像这样的邮递员示例:
在 NodeJS 中有可能吗?教我大师!非常感谢:)
答案 0 :(得分:0)
您可以使用请求模块轻松发布表单数据,例如:
let request = require('request');
let fs = require("fs");
let url = "http://httpbin.org/post";
var fileName = process.argv[2] || 'test.png';
let formData = {
upload_file: {
value: fs.readFileSync(fileName),
options: {
filename: fileName,
contentType: 'image/png'
}
}
};
request.post({ url: url, formData: formData}, (err, httpResponse, body) => {
if (err) {
console.error("Upload failed: ", err);
}
console.log('Upload successful: response: ', body);
});
如果要编写一个简单的服务器来接收文件,它将看起来像这样:
const express = require('express');
const multer = require('multer');
const upload = multer();
const fs = require('fs');
var app = express();
app.set('port', 3000);
app.post('/post_image', upload.any(), (req, res) => {
console.log('POST /post_image/');
console.log('Headers: ', req.headers)
fs.writeFileSync('uploaded_image.png', req.files[0].buffer);
res.status(200).send('ok');
});
app.listen(app.get('port'));