const multer = require('multer'); const csv = require('csv-parser'); const fs = require('fs'); const upload = multer({ dest: '../temp-files', limits: { fileSize: 5 * 1024 * 1024 }, // 限制文件大小为5MB fileFilter: (req, file, cb) => { if (file.mimetype === 'text/csv' || file.originalname.endsWith('.csv')) { cb(null, true); } else { cb(new Error('只允许上传CSV文件')); } } }); function useUploadFileParse(app) { app.post('/upload-drug-csv', upload.single('file'), async (req, res) => { if (!req.file) { return res.status(400).json({ success: false, message: 'No file uploaded' }); } const operator = typeof req.body.operator === 'string' ? req.body.operator : ''; const operatorId = typeof req.body.operatorId === 'string' ? req.body.operatorId : ''; const onSale = req.body.onSale === 'true' || req.body.onSale === true; if (!operator || !operatorId) { return res.json({ success: false, message: '参数错误' }); } const { getBatchInsertDrugFn } = require('../hlw/drug-info/batch-upload'); const { batchInsertDrug, getCount, flushBatch } = await getBatchInsertDrugFn(); const extraInfo = { creator: operator, creatorId: operatorId, createTime: Date.now(), onSale }; fs.createReadStream(req.file.path) .pipe(csv()) .on('data', (data) => batchInsertDrug(data, extraInfo)) .on('end', async () => { await flushBatch(); const count = await getCount(); fs.unlinkSync(req.file.path); // 删除临时文件 res.json({ success: count > 0, message: count > 0 ? `成功导入 ${count} 条药品信息` : '没有导入任何药品信息', }); }) .on('error', (err) => { res.status(500).json({ success: false, message: err.message }); }); }); // 配送/线上购药药品库导入:写入 online-drug-info 集合 app.post('/upload-online-drug-csv', upload.single('file'), async (req, res) => { if (!req.file) { return res.status(400).json({ success: false, message: 'No file uploaded' }); } const operator = typeof req.body.operator === 'string' ? req.body.operator : ''; const operatorId = typeof req.body.operatorId === 'string' ? req.body.operatorId : ''; const onSale = req.body.onSale === 'true' || req.body.onSale === true; if (!operator || !operatorId) { return res.json({ success: false, message: '参数错误' }); } const { getBatchInsertOnlineDrugFn } = require('../hlw/online-drug-info/batch-upload'); const { batchInsertDrug, getCount, flushBatch } = await getBatchInsertOnlineDrugFn(); const extraInfo = { creator: operator, creatorId: operatorId, createTime: Date.now(), onSale }; fs.createReadStream(req.file.path) .pipe(csv()) .on('data', (data) => batchInsertDrug(data, extraInfo)) .on('end', async () => { await flushBatch(); const count = await getCount(); fs.unlinkSync(req.file.path); // 删除临时文件 res.json({ success: count > 0, message: count > 0 ? `成功导入 ${count} 条线上药品信息` : '没有导入任何药品信息', }); }) .on('error', (err) => { res.status(500).json({ success: false, message: err.message }); }); }); } module.exports = { useUploadFileParse }