54 lines
1.5 KiB
JavaScript
54 lines
1.5 KiB
JavaScript
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,
|
|
}
|