我需要將此卷曲轉換為 axios。
url -X POST "https://apis.aligo.in/send/" \
--data-urlencode "key=xxxxx" \
--data-urlencode "user_id=xxxxx" \ \
--data-urlencode "rdate=20211222" \
--form image=@localfilename
好的,所以我用nodejs.
axios.post(url, null, {
key: ***, user_id: ***, rdate: ***
})
一切正常,但我不知道如何轉換所說的image部分curl。
--form image=@localfilename
此外,我不想放置本地影像,我只有 URL
const myimg = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Cat03.jpg/481px-Cat03.jpg"
我可以只下載它并更改為 blob 并發送嗎?你能寫一個例子嗎?
uj5u.com熱心網友回復:
在我看來,您需要使用 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' });
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/392913.html
上一篇:Libcurl-CURLMOPT_TIMERFUNCTION-它是做什么用的?
下一篇:如何填寫表單并將其提交到不同的域
