在以下代码段中,我使用node-fetch和form-data首先从远程 URL 检索图像文件,然后将其上传到 S3 存储桶(在不同的脚本中使用aws-sdk和multer):import fetch from 'node-fetch';import fs from 'fs';import FormData from 'form-data';const form = new FormData();const processProfileImg = (imageURL, userID) => { fetch(imageURL, userID) .then((response) => { const dest = fs.createWriteStream(`./temp/${userID}.jpg`); response.body.pipe(dest); }) .then((dest) => { form.append('profileImage', fs.createReadStream(`./temp/${userID}.jpg`)); fetch(`https://www.schandillia.com/upload/profile-image?userID=${userID}`, { method: 'POST', body: form }) .then(response => response.json()) .then(json => console.log(json)); });};export default processProfileImg;问题是,这涉及一个中间步骤,即首先在检索时将文件存储在本地,然后再由form-data函数将其拾取以进行 POST 。有没有办法完全绕过这一步?我不想将文件保存在本地,我只想从远程 URL 中提取它并将其 POST 到上传路由,而无需创建本地文件。
2 回答
慕尼黑的夜晚无繁华
TA贡献1864条经验 获得超6个赞
这对我有用:
const axios = require('axios')
const FormData = require('form-data');
//Get image
let imageResponse = await axios({
url: imageUrl,
method: 'GET',
responseType: 'arraybuffer'
})
//Create form data
const form = new FormData()
form.append('image', imageResponse.data, {
contentType: 'image/jpeg',
name: 'image',
filename: 'imageFileName.jpg'
})
//Submit form
let result = await axios({
url: serverUrl,
method: "POST",
data: form,
headers: { "Content-Type": `multipart/form-data; boundary=${form._boundary}` }
})
添加回答
举报
0/150
提交
取消