You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何将二进制媒体数据转换为Buffer?

Fixing Binary Image Upload to Google Cloud Storage with Node.js Request Module

Hey there, let's work through getting your binary image uploaded to GCS correctly—here's what's going wrong and how to fix it:

Key Issues in Your Current Code

  • You’re declaring binaryData = data but then referencing fileBase64 in your formData—this variable mismatch is almost certainly causing problems.
  • new Buffer(data) is deprecated in modern Node.js versions; use Buffer.from() instead for safer, standard buffer creation.
  • If data is already raw binary from your third-party API, you don’t need to mess with base64—you can pass the buffer directly to your form data.

Corrected Code Example

// Assume `data` is the raw binary image received from the third-party API
const bufferData = Buffer.from(data); // Use the modern Buffer.from() method

request({
  method: "POST",
  url: '/endpoint/upload', // Confirm this is your valid GCS upload endpoint
  headers: {
    'cache-control': 'no-cache'
    // Let the request module auto-generate the multipart boundary instead of hardcoding it
  },
  formData: {
    filename: {
      value: bufferData, // Pass the binary buffer directly here
      options: {
        filename: 'test.jpg',
        contentType: 'image/jpeg'
      }
    }
  }
}, function(err, response, body){
  if (err) {
    console.error('Upload failed with error:', err);
    return;
  }
  console.log('Upload successful! Response:', body);
})

Quick Additional Tips

  • Validate Your Input: Double-check that data is actually raw binary (not a string or base64 encoded). If it is base64, decode it first with Buffer.from(data, 'base64').
  • Skip Manual Boundaries: Hardcoding the multipart boundary can lead to mismatches. The request module handles this automatically if you omit it from headers.
  • Add Error Handling: Catching network errors or invalid GCS responses will help you debug issues faster.

内容的提问来源于stack exchange,提问作者Amir Saleem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:28:22