用途
有时候,我们想要使用某个接口,但是该接口只允许传入 formData 数据,意味着我们得实际传入真实的图片文件。我们希望能通过传入 图片的网络地址 来实现该接口的调用情况时候。就得部署一个中间中转的服务器接口了。
这个 api 的目的就是为了接收网络图片,下载到本地。并将本地图片以正确的方式发给指定的接口;
思路
通过接口提供的网络图片地址,将图片下载到本地根目录下的 image 文件夹中
- 导入 form-data 包是用于发送 form-data 数据
const axios = require('axios');
const fs = require('fs');
const FormData = require('form-data');
async function downloadImage(url) {
const timestamp = new Date().getTime();
const imagePath = path.join(__dirname, `image/temp_${timestamp}.jpg`);
const writer = fs.createWriteStream(imagePath);
const response = await axios({
url: url,
method: 'GET',
responseType: 'stream'
});
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', () => resolve(imagePath));
writer.on('error', reject);
});
}
- 通过得到的本地图片,导入到 FromData 包, 以 formData 数据 发起 网络请求
const axios = require('axios');
const fs = require('fs');
const FormData = require('form-data');
async function sendRequest(url, imagePath) {
const form = new FormData();
form.append('image', fs.createReadStream(imagePath), { filename: path.basename(imagePath) });
form.append('model', 'anime');
form.append('force_one', '1');
const response = await axios.post(url, form, {
headers: form.getHeaders()
});
return response;
}
完整代码:
const express = require('express');
const axios = require('axios');
const fs = require('fs');
const FormData = require('form-data');
const path = require('path');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.post('/detect', async (req, res) => {
try {
const imageUrl = req.body.imageUrl;
// 下载图片文件
const imagePath = await downloadImage(imageUrl);
// 发送POST请求
const apiUrl = '目标url地址';
const response = await sendRequest(apiUrl, imagePath);
// 处理响应结果
res.send(response.data);
} catch (error) {
console.error(error);
res.status(500).send('Internal Server Error');
}
});
async function downloadImage(url) {
const timestamp = new Date().getTime();
const imagePath = path.join(__dirname, `image/temp_${timestamp}.jpg`);
const writer = fs.createWriteStream(imagePath);
const response = await axios({
url: url,
method: 'GET',
responseType: 'stream'
});
response.data.pipe(writer);
return new Promise((resolve, reject) => {
writer.on('finish', () => resolve(imagePath));
writer.on('error', reject);
});
}
async function sendRequest(url, imagePath) {
const form = new FormData();
form.append('image', fs.createReadStream(imagePath), { filename: path.basename(imagePath) });
const response = await axios.post(url, form, {
headers: form.getHeaders()
});
return response;
}
app.listen(port, () => {
console.log(`服务器运行在 http://localhost:${port}`);
});
说明
里面用到了 axios 提供的 pipe() 函数 和 fs 写入流的 fs.createWriteStream() 方法