如何使用NodeJS将图片URL转换为可发送的.png文件?
解决方案:将图片URL转为可上传的流文件
你不需要将图片保存到本地文件,直接通过Node.js获取图片的二进制流,即可传给目标API。以下是修改后的完整代码:
const axios = require('axios').default; const FormData = require("form-data"); async function checkExplicitContent(imageUrl) { try { // 从URL获取图片的响应流 const imageResponse = await axios.get(imageUrl, { responseType: 'stream' // 指定响应类型为流 }); // 创建FormData并添加字段 const form = new FormData(); form.append("providers", 'amazon, google'); // 将图片流添加到form,同时指定文件名和内容类型 form.append("file", imageResponse.data, { filename: 'image.png', // 根据实际URL后缀调整,比如jpg格式就改为image.jpg contentType: imageResponse.headers['content-type'] || 'image/png' }); // 发送请求到检测API const options = { method: 'POST', url: 'https://api.edenai.run/v2/image/explicit_content', headers: { authorization: 'Bearer 🔑 Your_API_Key', ...form.getHeaders() // 自动生成multipart/form-data所需的headers,含boundary }, data: form }; const response = await axios.request(options); console.log(response.data); return response.data; } catch (error) { console.error('请求出错:', error); throw error; } } // 调用示例 checkExplicitContent('https://replicate.delivery/pbxt/Y45OPyjFe92FLqemk1Mmsr69gzruylefj5SxKqJInMmxCyABB/out-0.png');
关键说明:
- 无需本地文件:通过
axios.get请求图片URL时设置responseType: 'stream',直接获取图片的可读流,避免磁盘IO操作。 - 正确识别文件格式:给
form.append的file字段额外传入文件名和内容类型,确保API能正确解析文件。 - 简化Headers配置:使用
form.getHeaders()自动生成multipart/form-data所需的请求头,无需手动拼接boundary。
如果需要兼容不支持流的场景,也可以先获取图片Buffer再转为可读流:
const { Readable } = require('stream'); // ... 其他代码不变 const imageResponse = await axios.get(imageUrl, { responseType: 'arraybuffer' // 获取图片Buffer }); // 将Buffer转为可读流 const imageStream = Readable.from(imageResponse.data); form.append("file", imageStream, { filename: 'image.png', contentType: imageResponse.headers['content-type'] || 'image/png' }); // ... 后续请求代码不变
内容的提问来源于stack exchange,提问作者Brian Mason
相关产品推荐
相关产品推荐

