Guest User

Untitled

a guest
Oct 17th, 2025
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import fs from 'fs';
  2. import fetch from 'node-fetch';
  3.  
  4. /**
  5.  * 使用 PUT 方法上传文件二进制
  6.  * @param {string} filePath 本地文件路径
  7.  * @param {string} fileName 上传时的文件名
  8.  * @param {string} url 上传接口地址(默认 http://127.0.0.1:8080/api/upload)
  9.  * @returns {Promise<string>} 响应的文件直链
  10.  */
  11. async function uploadFile(filePath, fileName, url = 'http://127.0.0.1:8080/api/upload') {
  12.     const fullUrl = `${url}?name=${encodeURIComponent(fileName)}`;
  13.     const fileData = fs.readFileSync(filePath);
  14.  
  15.     const response = await fetch(fullUrl, {
  16.         method: 'PUT',
  17.         body: fileData
  18.     });
  19.  
  20.     if (!response.ok) {
  21.         throw new Error(`上传失败:${response.status} ${response.statusText}`);
  22.     }
  23.  
  24.     return await response.text();
  25. }
  26.  
  27. (async () => {
  28.     console.log('开始上传')
  29.     try {
  30.         const res = await uploadFile('test.mp4', 'test.mp4');
  31.         console.log(`上传成功: ${res}`);
  32.     } catch (err) {
  33.         console.error(err);
  34.     }
  35. })();
  36.  
Advertisement
Add Comment
Please, Sign In to add comment