| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- const http = require('http');
- const fs = require('fs');
- const path = require('path');
- function uploadFile(filePath) {
- return new Promise((resolve, reject) => {
- const boundary = '----WebKitFormBoundary' + Math.random().toString(36).substring(2);
-
- const fileName = path.basename(filePath);
- const fileContent = fs.readFileSync(filePath);
-
- // 构建 multipart/form-data 请求体
- let body = `--${boundary}\r\n`;
- body += `Content-Disposition: form-data; name="file"; filename="${fileName}"\r\n`;
- body += `Content-Type: image/png\r\n\r\n`;
- body += fileContent;
- body += `\r\n`;
-
- body += `--${boundary}\r\n`;
- body += `Content-Disposition: form-data; name="type"\r\n\r\n`;
- body += `image\r\n`;
-
- body += `--${boundary}\r\n`;
- body += `Content-Disposition: form-data; name="name"\r\n\r\n`;
- body += `${fileName}\r\n`;
-
- body += `--${boundary}--\r\n`;
-
- const options = {
- hostname: 'localhost',
- port: 3000,
- path: '/api/video/materials/upload',
- method: 'POST',
- headers: {
- 'Content-Type': `multipart/form-data; boundary=${boundary}`,
- 'Content-Length': Buffer.byteLength(body)
- }
- };
-
- const req = http.request(options, (res) => {
- let data = '';
- res.on('data', chunk => data += chunk);
- res.on('end', () => {
- try {
- const json = JSON.parse(data);
- resolve({ status: res.statusCode, data: json });
- } catch (e) {
- resolve({ status: res.statusCode, data: data });
- }
- });
- });
-
- req.on('error', reject);
- req.write(body);
- req.end();
- });
- }
- (async () => {
- console.log('=== 测试文件上传 ===\n');
-
- // 使用项目根目录的 PNG 文件
- const testFile = 'C:/Users/caoyg/ai/audio-tts/audio_codebuddy/page1-home.png';
-
- if (!fs.existsSync(testFile)) {
- console.log('❌ 测试文件不存在:', testFile);
- return;
- }
-
- console.log('测试文件:', testFile);
- console.log('文件大小:', fs.statSync(testFile).size, 'bytes\n');
-
- try {
- const result = await uploadFile(testFile);
- console.log('状态码:', result.status);
- console.log('响应:', JSON.stringify(result.data, null, 2));
-
- if (result.status === 200 && result.data.success) {
- console.log('\n✅ 上传成功!');
- } else {
- console.log('\n❌ 上传失败');
- }
- } catch (e) {
- console.error('❌ 请求失败:', e.message);
- }
- })();
|