109 lines
3.1 KiB
JavaScript
109 lines
3.1 KiB
JavaScript
import { Router } from 'express';
|
|
const router = Router();
|
|
import { statSync, createReadStream, existsSync, mkdirSync, unlinkSync } from 'fs';
|
|
import { join, dirname, extname } from 'path';
|
|
import { fileURLToPath } from 'url'; // 添加这行
|
|
import multer, { diskStorage } from 'multer';
|
|
import axios from 'axios';
|
|
import FormData from 'form-data';
|
|
|
|
const apikey = '3c20cd6c85514d1c86d55a5d3bcd53b7'
|
|
|
|
/**
|
|
* 上传文件到外部平台
|
|
* @param {string} filePath
|
|
* @returns {Promise<string|null>} 文件名或null
|
|
*/
|
|
async function send_file(filePath) {
|
|
try {
|
|
const url = 'https://www.runninghub.cn/task/openapi/upload';
|
|
|
|
// 使用 form-data 库创建表单数据
|
|
const form = new FormData();
|
|
const fileStats = statSync(filePath);
|
|
console.log(`文件大小: ${fileStats.size} bytes`);
|
|
console.log(`文件路径: ${filePath}`);
|
|
|
|
form.append('file', createReadStream(filePath));
|
|
form.append('apiKey', apikey);
|
|
form.append('fileType', 'input');
|
|
|
|
const response = await axios.post(url, form, {
|
|
headers: {
|
|
...form.getHeaders(), // 重要:使用 form-data 提供的头部信息
|
|
"Host": "www.runninghub.cn",
|
|
},
|
|
timeout: 30000,
|
|
});
|
|
|
|
console.log('****************************11*******************************');
|
|
console.log(response.data);
|
|
|
|
if (response.data.code === 0 && response.data.msg === "success") {
|
|
console.log("File URL:", response.data.data.fileName);
|
|
return response.data.data.fileName;
|
|
}
|
|
else if (response.data.code === 301 && response.data.msg === "PARAMS_INVALID") {
|
|
console.log("请重新上传文件");
|
|
return false;
|
|
}
|
|
else {
|
|
console.log("请重新上传文件");
|
|
return false;
|
|
}
|
|
} catch (error) {
|
|
console.error('文件上传失败:', error);
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// 使用 fileURLToPath 获取目录路径
|
|
const __filename = fileURLToPath(import.meta.url);
|
|
const __dirname = dirname(__filename);
|
|
|
|
// 确保文件目录存在
|
|
const uploadDir = join(__dirname, '../uploads');
|
|
if (!existsSync(uploadDir)) {
|
|
mkdirSync(uploadDir, { recursive: true });
|
|
}
|
|
|
|
// 配置multer存储
|
|
const storage = diskStorage({
|
|
destination: function (req, file, cb) {
|
|
cb(null, uploadDir);
|
|
},
|
|
filename: function (req, file, cb) {
|
|
const randomStr = Math.random().toString(36).substring(2, 8);
|
|
cb(null, `${Date.now()}-${randomStr}${extname(file.originalname)}`);
|
|
}
|
|
});
|
|
|
|
const upload = multer({ storage: storage });
|
|
|
|
// 文件上传接口
|
|
router.post('/upload', upload.single('file'), async (req, res) => {
|
|
if (!req.file) {
|
|
return res.status(400).json({ error: 'No file uploaded' });
|
|
}
|
|
|
|
try {
|
|
// 调用外部平台接口
|
|
const result = await send_file(req.file.path);
|
|
// 删除本地文件
|
|
unlinkSync(req.file.path);
|
|
|
|
if (result) {
|
|
res.json({
|
|
success: true,
|
|
url: result
|
|
});
|
|
} else {
|
|
res.status(500).json({ error: 'File upload to external service failed' });
|
|
}
|
|
} catch (error) {
|
|
console.error('处理失败:', error);
|
|
res.status(500).json({ error: '文件处理失败' });
|
|
}
|
|
});
|
|
|
|
export default router; |