diff --git a/ejsExcel.js b/ejsExcel.js index c125ff1..d5d9b17 100644 --- a/ejsExcel.js +++ b/ejsExcel.js @@ -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) { @@ -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)) { diff --git a/lib/http.js b/lib/http.js new file mode 100644 index 0000000..d8245dc --- /dev/null +++ b/lib/http.js @@ -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); + }); + }); +}