Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

增加http、https前缀开头的图片加载 #80

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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);
});
});
}