Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions ejsExcel.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const Hzip = require("./lib/hzip");
const xml2json = require("./lib/xml2json");
const xmldom = require("./lib/xmldom");
const ejs4xlx = require("./ejs4xlx");
const {downloadImageToBuffer} = require('./lib/http');

const isType = function (type) {
return function (obj) {
Expand Down Expand Up @@ -442,11 +443,20 @@ async function renderExcel(exlBuf, _data_, opt) {
return "";
}
if (isString(imgPh)) {
try {
imgBuf = await readFileAsync(imgPh);
} catch (error) {
err = error;
return "";
if(imgPh.startsWith('http://') || imgPh.startsWith('https://')){
try {
imgBuf = await downloadImageToBuffer(imgPh);
} catch (error) {
err = error;
return "";
}
} else {
try {
imgBuf = await readFileAsync(imgPh);
} catch (error) {
err = error;
return "";
}
}
imgBaseName = path.basename(imgPh);
} else if (Buffer.isBuffer(imgPh)) {
Expand Down
39 changes: 39 additions & 0 deletions lib/http.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const http = require('http');
const https = require('https');
const URL = require('url').URL;
exports.downloadImageToBuffer = async function (url) {
return new Promise((resolve, reject) => {
const parsedUrl = new URL(url);
const moduleToUse = parsedUrl.protocol === 'https:' ? https : http;

const request = moduleToUse.get(url, response => {
if (response.statusCode !== 200) {
reject(new Error(`Failed to get image, status code: ${response.statusCode}`));
}

// 创建一个空的Buffer来累积数据块
let chunks = [];

response.on('data', chunk => {
chunks.push(chunk);
});

response.on('end', () => {
try {
const buffer = Buffer.concat(chunks);
resolve(buffer);
} catch (error) {
reject(error);
}
});

response.on('error', error => {
reject(error);
});
});

request.on('error', error => {
reject(error);
});
});
}