POSTされたファイル名をそのままアップロードできるよう修正しました。
const express = require('express');
const multer = require('multer');
const OSS = require('ali-oss');
const app = express();
const fs = require('fs');
const uploadDir = 'uploads/';
// 检查 uploads 目录是否存在,如果不存在则创建
if (!fs.existsSync(uploadDir)){
fs.mkdirSync(uploadDir);
}
// 自定义 Multer 存储引擎,以保留原始文件名
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/');
},
filename: function (req, file, cb) {
cb(null, file.originalname); // 使用原始文件名
}
});
// // 配置 Multer,用于存储上传的文件
// const upload = multer({ dest: 'uploads/' });
// 配置阿里云 OSS 客户端
const client = new OSS({
region: 'oss-cn-hongkong',
bucket: 'corpusmaker',
accessKeyId: "LTAI5tMdAL7XMobqcWDfEtR3",
accessKeySecret: "~~~~"
});
const upload = multer({ storage: storage });
// 上传文件到 OSS
async function saveFileToOSS(filePath, filename) {
try {
let result = await client.put(filename, filePath);
console.log('OSS File URL:', result.url);
return result.url;
} catch (error) {
console.error('Error uploading to OSS:', error);
throw error;
}
}
// 处理 POST 请求
app.post('/api/v1/save', upload.single('file'), async (req, res) => {
if (!req.file) {
return res.status(400).send('No file uploaded.');
}
try {
// 上传文件到 OSS,并且文件名和原文件名一致
const url = await saveFileToOSS(req.file.path, req.file.filename);
res.send(`File uploaded to OSS: ${url}`);
} catch (error) {
res.status(500).send('Error uploading file to OSS.');
}
});
const port = 3000
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});