Node.js中用Got流式传输远程URL数据至另一API(无需本地存储)
直接流式转发远程图片到目标API
你可以直接将Got Stream API返回的可读流作为Axios POST请求的请求体,完全跳过本地文件存储步骤,核心是利用Node.js流的管道特性,直接在两个HTTP请求之间传递数据。
基础实现代码
const got = require('got'); const axios = require('axios'); const imageUrl = "https://media0.giphy.com/media/4SS0kfzRqfBf2/giphy.gif"; const targetApiUrl = 'post_url'; async function forwardImage() { try { // 直接将Got的可读流作为Axios请求体发送 const response = await axios.post(targetApiUrl, got.stream(imageUrl), { headers: { // 根据图片实际类型设置Content-Type,这里示例为GIF格式 'Content-Type': 'image/gif' } }); console.log('转发成功:', response.data); } catch (error) { console.error('转发失败:', error.message); } } forwardImage();
进阶:自动匹配Content-Type
如果不确定图片的MIME类型,可以先获取Got响应的Content-Type头,再传递给目标API,适配不同类型的图片:
const got = require('got'); const axios = require('axios'); const imageUrl = "https://media0.giphy.com/media/4SS0kfzRqfBf2/giphy.gif"; const targetApiUrl = 'post_url'; async function forwardImage() { try { const imageStream = got.stream(imageUrl); // 等待获取响应头,拿到图片的Content-Type await new Promise((resolve, reject) => { imageStream.on('response', (res) => { resolve(res.headers['content-type']); }); imageStream.on('error', reject); }); // 发送请求,自动使用图片原有的Content-Type const response = await axios.post(targetApiUrl, imageStream, { headers: { 'Content-Type': imageStream.response.headers['content-type'] } }); console.log('转发成功:', response.data); } catch (error) { console.error('转发失败:', error.message); } } forwardImage();
关键说明
- 移除了本地文件写入(
createWriteStream)和读取(fs.createReadStream)的冗余步骤,直接通过流在两个HTTP请求间传递数据,节省磁盘IO和存储空间。 - Axios支持直接接收可读流作为请求体,底层会自动处理流的消费逻辑。
- 必须确保目标API支持接收原始二进制流作为请求体,如果API要求通过表单上传(如
multipart/form-data),则需要将流包装到FormData对象中再发送。
内容的提问来源于stack exchange,提问作者Sufail Kalathil
相关产品推荐
相关产品推荐

