// 确保上传目录存在
const uploadDir = path.join(__dirname, '../uploads');
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir);
}
// 设置文件存储
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, uploadDir);
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
// 上传音乐文件
router.post('/upload', upload.fields([{ name: 'audioFile' }, { name: 'coverImage' }]), async (req, res) => {
try {
if (!req.files.audioFile) {
throw new Error('No audio file uploaded');
}
const audioFile = req.files.audioFile[0];
const coverImageFile = req.files.coverImage ? req.files.coverImage[0] : null;
const { originalname, filename: audioFileName } = audioFile;
const title = Buffer.from(originalname, 'latin1').toString('utf8').split('.').slice(0, -1).join('.');
const audioFilePath = `http://localhost:3001/uploads/${audioFileName}`;
const coverImagePath = coverImageFile ? `http://localhost:3001/uploads/${coverImageFile.filename}` : null;
console.log('File uploaded:', audioFile); // 添加日志记录
const newSong = await Song.create({
title,
artist: req.body.artist || 'Unknown', // 可以根据需要修改
path: audioFilePath,
coverImagePath: coverImagePath,
coverImage: coverImageFile ? fs.readFileSync(coverImageFile.path) : null,
audioData: fs.readFileSync(audioFile.path),
lyrics: null
});
res.status(200).json({ message: 'File uploaded successfully', song: newSong });
} catch (error) {
console.error('Error uploading song:', error); // 添加错误日志
res.status(500).json({ error: 'Failed to upload song' });
}
});
报错图片
