test-upload.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. const http = require('http');
  2. const fs = require('fs');
  3. const path = require('path');
  4. function uploadFile(filePath) {
  5. return new Promise((resolve, reject) => {
  6. const boundary = '----WebKitFormBoundary' + Math.random().toString(36).substring(2);
  7. const fileName = path.basename(filePath);
  8. const fileContent = fs.readFileSync(filePath);
  9. // 构建 multipart/form-data 请求体
  10. let body = `--${boundary}\r\n`;
  11. body += `Content-Disposition: form-data; name="file"; filename="${fileName}"\r\n`;
  12. body += `Content-Type: image/png\r\n\r\n`;
  13. body += fileContent;
  14. body += `\r\n`;
  15. body += `--${boundary}\r\n`;
  16. body += `Content-Disposition: form-data; name="type"\r\n\r\n`;
  17. body += `image\r\n`;
  18. body += `--${boundary}\r\n`;
  19. body += `Content-Disposition: form-data; name="name"\r\n\r\n`;
  20. body += `${fileName}\r\n`;
  21. body += `--${boundary}--\r\n`;
  22. const options = {
  23. hostname: 'localhost',
  24. port: 3000,
  25. path: '/api/video/materials/upload',
  26. method: 'POST',
  27. headers: {
  28. 'Content-Type': `multipart/form-data; boundary=${boundary}`,
  29. 'Content-Length': Buffer.byteLength(body)
  30. }
  31. };
  32. const req = http.request(options, (res) => {
  33. let data = '';
  34. res.on('data', chunk => data += chunk);
  35. res.on('end', () => {
  36. try {
  37. const json = JSON.parse(data);
  38. resolve({ status: res.statusCode, data: json });
  39. } catch (e) {
  40. resolve({ status: res.statusCode, data: data });
  41. }
  42. });
  43. });
  44. req.on('error', reject);
  45. req.write(body);
  46. req.end();
  47. });
  48. }
  49. (async () => {
  50. console.log('=== 测试文件上传 ===\n');
  51. // 使用项目根目录的 PNG 文件
  52. const testFile = 'C:/Users/caoyg/ai/audio-tts/audio_codebuddy/page1-home.png';
  53. if (!fs.existsSync(testFile)) {
  54. console.log('❌ 测试文件不存在:', testFile);
  55. return;
  56. }
  57. console.log('测试文件:', testFile);
  58. console.log('文件大小:', fs.statSync(testFile).size, 'bytes\n');
  59. try {
  60. const result = await uploadFile(testFile);
  61. console.log('状态码:', result.status);
  62. console.log('响应:', JSON.stringify(result.data, null, 2));
  63. if (result.status === 200 && result.data.success) {
  64. console.log('\n✅ 上传成功!');
  65. } else {
  66. console.log('\n❌ 上传失败');
  67. }
  68. } catch (e) {
  69. console.error('❌ 请求失败:', e.message);
  70. }
  71. })();