Fix PDF: Cyrillic filenames (Latin-1→UTF-8), page count via pdf-lib

- Fix multer encoding: decode Latin-1 to UTF-8 for Cyrillic names
- Use pdf-lib instead of pdf-parse for page count (more reliable)
- ignoreEncryption flag for encrypted PDFs
This commit is contained in:
treamz 2026-03-22 01:20:11 +03:00
parent 75d6c186aa
commit ee49fed415

View File

@ -25,6 +25,16 @@ const upload = multer({
const limiter = rateLimit({ windowMs: 60000, max: 30, message: { error: 'Слишком много запросов' } }); const limiter = rateLimit({ windowMs: 60000, max: 30, message: { error: 'Слишком много запросов' } });
// Fix multer filename encoding (Latin-1 → UTF-8 for Cyrillic)
function fixFilename(str) {
try {
const buf = Buffer.from(str, 'latin1');
const decoded = buf.toString('utf8');
if (/[а-яёА-ЯЁ]/.test(decoded)) return decoded;
} catch {}
return str;
}
// File storage for uploaded PDFs // File storage for uploaded PDFs
const pdfFiles = new Map(); const pdfFiles = new Map();
@ -33,7 +43,7 @@ function registerFile(multerFile, pageCount) {
const entry = { const entry = {
id, id,
path: multerFile.path, path: multerFile.path,
name: multerFile.originalname, name: fixFilename(multerFile.originalname),
size: multerFile.size, size: multerFile.size,
pages: pageCount || 0, pages: pageCount || 0,
}; };
@ -68,18 +78,21 @@ router.get('/', (req, res) => {
router.post('/upload', limiter, upload.array('files', 10), async (req, res) => { router.post('/upload', limiter, upload.array('files', 10), async (req, res) => {
if (!req.files || !req.files.length) return res.status(400).json({ error: 'Файлы не загружены' }); if (!req.files || !req.files.length) return res.status(400).json({ error: 'Файлы не загружены' });
const pdfParse = require('pdf-parse');
const results = []; const results = [];
for (const file of req.files) { for (const file of req.files) {
let pages = 0; let pages = 0;
try { try {
if (file.mimetype === 'application/pdf') { if (file.mimetype === 'application/pdf' || file.originalname.endsWith('.pdf')) {
const buf = fs.readFileSync(file.path); const buf = fs.readFileSync(file.path);
const data = await pdfParse(buf); // Use pdf-lib for page count (more reliable than pdf-parse)
pages = data.numpages || 0; const { PDFDocument } = await import('pdf-lib');
const doc = await PDFDocument.load(buf, { ignoreEncryption: true });
pages = doc.getPageCount();
}
} catch (e) {
log.warn('PDF page count failed', { file: file.originalname, error: e.message });
} }
} catch {}
const entry = registerFile(file, pages); const entry = registerFile(file, pages);
results.push({ id: entry.id, name: entry.name, size: entry.size, pages }); results.push({ id: entry.id, name: entry.name, size: entry.size, pages });
} }