This commit is contained in:
payacom
2026-08-31 20:45:41 +03:30
parent fa9f23c61d
commit 3f416a7a60
367 changed files with 621895 additions and 6443 deletions

53
utils/postBase64Files.js Normal file
View File

@@ -0,0 +1,53 @@
const fs = require('fs')
const path = require('path')
function decodeBase64Buffer(data) {
if (!data || typeof data !== 'string') {
throw new Error('داده فایل نامعتبر است')
}
const payload = data.includes(',') ? data.split(',')[1] : data
if (!payload) {
throw new Error('داده base64 خالی است')
}
return Buffer.from(payload, 'base64')
}
async function saveBase64PostFiles(files, imageDir, videoDir, { allowEmpty = false } = {}) {
if (!Array.isArray(files) || files.length === 0) {
if (allowEmpty) return []
throw new Error('هیچ فایلی ارسال نشده است')
}
return Promise.all(
files.map(async (file, index) => {
if (!file?.data || !file?.type) {
throw new Error(`فایل ${index + 1} ناقص است`)
}
const buffer = decodeBase64Buffer(file.data)
if (!buffer.length) {
throw new Error(`فایل ${index + 1} خالی است`)
}
const dir = String(file.type).startsWith('video/') ? videoDir : imageDir
const safeName = path
.basename(file.name || `upload-${index}`)
.replace(/[^\w.\-()+\s]/g, '_')
const filename = `${Date.now()}-${index}-${safeName}`
const filePath = path.join(dir, filename)
await fs.promises.writeFile(filePath, buffer)
return {
path: filePath,
filename,
mimetype: file.type,
}
})
)
}
module.exports = {
decodeBase64Buffer,
saveBase64PostFiles,
}