簡體   English   中英

Node JS上傳二進制文件到另一台服務器

[英]Node JS upload binary file to another server

我有一個音頻文件,我將其發布到服務器進行翻譯。 我設法在郵遞員中創建了一個請求,但我不知道如何將文件寫入此服務器。 下面是我到目前為止得到的代碼:

var http = require("https");

var options = {}

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
   });
});

options{}充滿了方法/主機名/當然的端口。 在郵遞員中,我添加了“二進制”文件,但我無法弄清楚如何將文件寫入 Node JS 中的請求。

一種無需太多工作即可輕松融入您當前程序的解決方案是使用 npm 上的form-data模塊。

表單數據模塊簡化了節點中的多部分請求。 下面是一個如何使用的簡單示例。

var http = require("https");
var FormData = require('form-data');
var fs = require('fs')

var form = new FormData();
form.append('my_field', fs.createReadStream('my_audio.file'));

var options = {
  host: 'your.host',
  port: 443,
  method: 'POST',
  // IMPORTANT!
  headers: form.getHeaders()
}

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
   });
});

// Pipe form to request
form.pipe(req);

在“真實世界”的場景中,您需要進行更多的錯誤檢查。 此外,npm 上還有許多其他 http 客戶端也使這個過程變得簡單(請求模塊使用表單數據 BTW)。 查看請求,如果您有興趣,就會得到

對於發送二進制請求,基本原理仍然相同, req可寫流 因此,您可以將數據通過pipe傳輸到流中,或者直接使用req.write(data)寫入。 這是一個例子。

var http = require('https');
var fs = require('fs');

var options = {
  // ...
  headers: {
    'Content-Type': 'application/octet-stream'
  }
}

var req = http.request(options, function (res) {
  var chunks = [];

  res.on("data", function (chunk) {
    chunks.push(chunk);
  });

  res.on("end", function () {
    var body = Buffer.concat(chunks);
    console.log(body.toString());
   });
});


var audioFile = fs.createReadStream('my_audio.file', { encoding: 'binary' });
audioFile.pipe(req);

注意,如果你顯式地使用write方法req.write(data)你必須調用req.end() 此外,您可能想查看 Node 的Buffer ( docs ) 的編碼選項。

您可以在 npm 上使用請求包。

從 npm 安裝request模塊: npm install request --save

然后使用請求模塊發送您的請求。

有關實施的詳細信息, https://www.npmjs.com/package/request查看https://www.npmjs.com/package/request

謝謝@undefined,您的回答對我很有幫助。

我正在發布我的解決方案,該解決方案對我使用 axios 將文件發送到另一台服務器有用。 忽略類型規范,我為我的項目啟用了 Typescript。

export const fileUpload: RequestHandler = async (req: Request, res: Response, next: NextFunction) => {
    const chunks: any[] = [];
    req.on('data', (chunk) => chunks.push(chunk));
    req.on('end', () => {
        const data = Buffer.concat(chunks);
        axios.put("ANOTHER_SERVER_URL", data).then((response) => {
            console.log('Success', response);
        }).catch(error => {            
            console.log('Failure', error);
        });
    });
    return res.status(200).json({});
};

謝謝,希望有幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM