import axios from 'axios'; import fs from 'fs'; import path from 'path'; const JINGROW_SERVER_URL = process.env.JINGROW_SERVER_URL; const PUBLIC_FILES_DIR = path.join(process.cwd(), 'public/files'); if (!fs.existsSync(PUBLIC_FILES_DIR)) { fs.mkdirSync(PUBLIC_FILES_DIR, { recursive: true }); } async function downloadToLocal(fileUrl) { try { let fullUrl = fileUrl; if (!/^https?:\/\//.test(fileUrl)) { fullUrl = `${JINGROW_SERVER_URL}${fileUrl}`; } const fileName = path.basename(fullUrl.split('?')[0]); const localPath = path.join(PUBLIC_FILES_DIR, fileName); const localUrl = `/files/${fileName}`; if (!fs.existsSync(localPath)) { const response = await axios.get(fullUrl, { responseType: 'stream' }); await new Promise((resolve, reject) => { const writer = fs.createWriteStream(localPath); response.data.pipe(writer); writer.on('finish', resolve); writer.on('error', reject); }); } return localUrl; } catch (e) { return fileUrl; } } // 提取富文本中的所有图片链接 function extractImageUrlsFromHtml(html) { if (!html) return []; const regex = /]+src=["']([^"'>]+)["']/g; const urls = []; let match; while ((match = regex.exec(html)) !== null) { urls.push(match[1]); } return urls; } // 替换富文本中的图片链接为本地路径 async function replaceImageUrlsInHtml(html) { if (!html) return html; const regex = /]+)src=["']([^"'>]+)["']/g; return await html.replace(regex, async (match, pre, url) => { const localUrl = await downloadToLocal(url); return `