在nodejs中使用axios下载图像
download image using axios in nodejs
const {Buffer} = require("buffer")
const express = require("express");
const axios = require("axios");
const app = express();
let url =
"https://res.cloudinary.com/practicaldev/image/fetch/s--nh8zSFgY--/c_fill,f_auto,fl_progressive,h_320,q_auto,w_320/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/285604/94170c66-2590-4002-90e0-ec4dc94ed7b5.png";
app.get("/", async(request, response) => {
const arrayBuffer = await axios.get(url);
let buffer = Buffer.from(arrayBuffer.data,'binary').toString("base64");
let image = `data:${arrayBuffer.headers["content-type"]};base64,${buffer}`;
response.send(`<img src=${image}/>`);
});
app.listen(5001, () => console.log("Server is up and running.."));
图像未显示。后台控制台没有报错。缓冲区是有效的 base64 字符串。
输出
您遗漏了两件事:
1.) 在您的请求选项中添加 responseType: 'arraybuffer'
2.) 将 base64
字符串周围缺少的引号添加到 img
标签中的 src
属性:
app.get("/", async(request, response) => {
const arrayBuffer = await axios.get(url, {
responseType: 'arraybuffer'
});
let buffer = Buffer.from(arrayBuffer.data,'binary').toString("base64");
let image = `data:${arrayBuffer.headers["content-type"]};base64,${buffer}`;
response.send(`<img src="${image}"/>`);
});
const {Buffer} = require("buffer")
const express = require("express");
const axios = require("axios");
const app = express();
let url =
"https://res.cloudinary.com/practicaldev/image/fetch/s--nh8zSFgY--/c_fill,f_auto,fl_progressive,h_320,q_auto,w_320/https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/285604/94170c66-2590-4002-90e0-ec4dc94ed7b5.png";
app.get("/", async(request, response) => {
const arrayBuffer = await axios.get(url);
let buffer = Buffer.from(arrayBuffer.data,'binary').toString("base64");
let image = `data:${arrayBuffer.headers["content-type"]};base64,${buffer}`;
response.send(`<img src=${image}/>`);
});
app.listen(5001, () => console.log("Server is up and running.."));
图像未显示。后台控制台没有报错。缓冲区是有效的 base64 字符串。
输出
您遗漏了两件事:
1.) 在您的请求选项中添加 responseType: 'arraybuffer'
2.) 将 base64
字符串周围缺少的引号添加到 img
标签中的 src
属性:
app.get("/", async(request, response) => {
const arrayBuffer = await axios.get(url, {
responseType: 'arraybuffer'
});
let buffer = Buffer.from(arrayBuffer.data,'binary').toString("base64");
let image = `data:${arrayBuffer.headers["content-type"]};base64,${buffer}`;
response.send(`<img src="${image}"/>`);
});