From f3c3832ff0495873f6f4240f2f3f3aa23d7d9753 Mon Sep 17 00:00:00 2001 From: dedede <263209441@qq.com> Date: Tue, 18 Jun 2024 21:46:05 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0http=E3=80=81https=E5=89=8D?= =?UTF-8?q?=E7=BC=80=E5=BC=80=E5=A4=B4=E7=9A=84=E5=9B=BE=E7=89=87=E5=8A=A0?= =?UTF-8?q?=E8=BD=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ejsExcel.js | 20 +++++++++++++++----- lib/http.js | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 5 deletions(-) create mode 100644 lib/http.js 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); + }); + }); +}