在我看来,你需要用axios下载一张图片,然后同时上传同一张图片。那里有很多例子。
因此,您需要以某种方式获取图像。下载它的替代方法是将其存储到内存中。 Axios 仅在浏览器环境中支持blob,因此您可以尝试使用ArrayBuffer 来存储图像,方法是将responseType 设置为arraybuffer(对于较大的文件stream 应该更好,但这需要有一个将流保存到的文件)。
将图像作为 ArrayBuffer 获取后,需要将其编码为字符串以允许包含到 JSON 对象中,然后将其作为请求正文传递给 Axios(并在处理上传的服务器上读取,因此读取服务器上的图像应该需要解码图像字符串)。
代码如下:
const axios = require('axios');
async function getImage() {
// image url
const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/481px-Cat03.jpg';
// get the image from the url
let imageArrayBuffer;
try {
imageArrayBuffer = await axios({
method: 'GET',
url: imageUrl,
// from the docs: https://github.com/axios/axios
// `responseType` indicates the type of data that the server will respond with
// options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
// browser only: 'blob'
responseType: 'arraybuffer'
});
} catch (err) {
console.error('error getting image', err);
// handleErrorSomewhere();
return;
}
// now upload the image
// to be able to include ArrayBuffer into a JSON, decode the buffer and encode image as string
const image = Buffer.from(imageArrayBuffer.data, 'binary').toString('base64');
// setup your upload url
const uploadUrl = 'https://apis.aligo.in/send/';
// prepare the body
const body = {
key: '',
user_id: '',
rdate: '',
// string image
image,
};
// upload the image and the rest
axios.post(uploadUrl, body);
}
// run the thing
getImage()
在服务器上(带有 Express 的 Node.js):
router.post('/send', (req, res) => {
// decode image
const image = new Buffer.from(req.body.image, 'base64');
const fs = require('fs');
const image = new Buffer.from(req.body.image, 'base64');
fs.writeFile('image.jpg', image , (err) => {
console.log('image saved');
res.status(200).json({ message: 'Thank you' });
});