diff --git a/routes/pdf.js b/routes/pdf.js index 36f76e5..da3f9a4 100644 --- a/routes/pdf.js +++ b/routes/pdf.js @@ -25,6 +25,16 @@ const upload = multer({ 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 const pdfFiles = new Map(); @@ -33,7 +43,7 @@ function registerFile(multerFile, pageCount) { const entry = { id, path: multerFile.path, - name: multerFile.originalname, + name: fixFilename(multerFile.originalname), size: multerFile.size, pages: pageCount || 0, }; @@ -68,18 +78,21 @@ router.get('/', (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: 'Файлы не загружены' }); - const pdfParse = require('pdf-parse'); const results = []; for (const file of req.files) { let pages = 0; try { - if (file.mimetype === 'application/pdf') { + if (file.mimetype === 'application/pdf' || file.originalname.endsWith('.pdf')) { const buf = fs.readFileSync(file.path); - const data = await pdfParse(buf); - pages = data.numpages || 0; + // Use pdf-lib for page count (more reliable than pdf-parse) + const { PDFDocument } = await import('pdf-lib'); + const doc = await PDFDocument.load(buf, { ignoreEncryption: true }); + pages = doc.getPageCount(); } - } catch {} + } catch (e) { + log.warn('PDF page count failed', { file: file.originalname, error: e.message }); + } const entry = registerFile(file, pages); results.push({ id: entry.id, name: entry.name, size: entry.size, pages }); }