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

Google Drive API文件上传失败(ECONNRESET错误)排查求助

Fixing ECONNRESET Error When Uploading Files to Google Drive v3 API with fs.createReadStream

Hey there! That ECONNRESET error you're seeing is super common when working with streams and API uploads, especially when switching from static text content to file streams. Let's break down the most likely causes and how to fix them:

1. Incorrect File Path (Most Common)

When using fs.createReadStream('photo4.txt'), Node.js looks for the file in your current working directory (the directory you ran the script from), not the directory where your script is saved. This is the #1 reason streams fail while static text works.

Fix: Use an absolute path with __dirname to ensure Node finds the right file:

const path = require('path');
// ...
const readStream = fs.createReadStream(path.join(__dirname, 'photo4.txt'));

Don't forget to require the path module at the top of your script!

2. Unhandled Stream Errors

If your file is missing, corrupted, or you don't have read permissions, the stream will throw an error that might not surface directly in the Drive API callback. This can cause the connection to drop abruptly, resulting in ECONNRESET.

Fix: Add an error listener to your read stream to catch these issues:

const readStream = fs.createReadStream(path.join(__dirname, 'photo4.txt'));
readStream.on('error', (err) => {
  console.error('File stream error:', err);
  // Handle the error appropriately (e.g., exit, retry)
});

This will tell you if the problem is with the file itself, not the API request.

3. Missing Content-Length Header

While most APIs handle stream uploads automatically, Google Drive's API sometimes expects explicit content-length for file streams. Without it, the API might not know when the stream ends, leading to a hung connection.

Fix: Fetch the file size first and set the Content-Length header:

const filePath = path.join(__dirname, 'photo4.txt');
fs.stat(filePath, (err, stats) => {
  if (err) {
    console.error('Failed to get file details:', err);
    return;
  }

  const media = {
    mimeType: 'text/plain',
    body: fs.createReadStream(filePath),
    headers: {
      'Content-Length': stats.size
    }
  };

  // Proceed with service.files.create...
});

4. Bonus: Clean Up Your Function Name

This isn't causing the error, but your function is named listFiles but handles file uploads—this can confuse future you (or collaborators!). Renaming it to uploadFile will make your code more maintainable.

Full Working Example

Here's a revised version of your code incorporating all these fixes:

const fs = require('fs');
const path = require('path');
const google = require('googleapis');

function uploadFile(auth) {
  const service = google.drive('v3');
  const filePath = path.join(__dirname, 'photo4.txt');

  fs.stat(filePath, (err, stats) => {
    if (err) {
      console.error('Error accessing file:', err);
      return;
    }

    const fileMetadata = {
      name: 'My Report4'
    };

    const readStream = fs.createReadStream(filePath);
    readStream.on('error', (streamErr) => {
      console.error('File stream failed:', streamErr);
    });

    const media = {
      mimeType: 'text/plain',
      body: readStream,
      headers: {
        'Content-Length': stats.size
      }
    };

    service.files.create({
      auth: auth,
      resource: fileMetadata,
      media: media,
      fields: 'id'
    }, (err, file) => {
      if (err) {
        console.error('Drive API upload error:', err);
      } else {
        console.log('Success! File Id:', file.id);
      }
    });
  });
}

Why Static Text Works but Streams Don't

When you pass a string like body: 'Any text', the API receives a complete, predictable chunk of data with a known length. Streams, however, send data in chunks. If the stream fails (e.g., file not found) or the API can't detect when the stream ends, the connection gets reset—hence the ECONNRESET error.

内容的提问来源于stack exchange,提问作者Sagar Chaudhary

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:23:34