首页 > 解决方案 > 如何使用 http(s) 模块在 Node.js 的请求中发送文件?

问题描述

我需要在 Node.js 中将文件作为POST请求的一部分发送,并且我不想使用其他包或外部库,而是使用普通http( https) 模块,这是标准 Node.js API 的一部分。

来自 Node.js 文档,一个示例

Node.js 文档中的这个示例暗示了我想要实现的目标:

const postData = querystring.stringify({'msg': 'Hello World!'});

const options = {
  hostname: 'http://localhost',
  port: 8080,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': Buffer.byteLength(postData)
  }
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(postData);
req.end();

我想要的是

这个例子非常接近我想要实现的,唯一的区别在于第一行:

const postData = querystring.stringify({'msg': 'Hello World!'}); // <== I want to send a file

我想发送一个文件,而不是发送一个字符串。文档页面说应该可以:

http.request()返回该类的一个实例http.ClientRequest。该ClientRequest实例是一个可写流。如果需要通过POST请求上传文件,则写入ClientRequest对象。

我怎样才能做到这一点?


尝试

我努力了:

clientRequest.write(fs.createReadStream("C:/Users/public/myfile.txt"));
clientRequest.end();

但我得到这个错误:

TypeError [ERR_INVALID_ARG_TYPE]:第一个参数必须是字符串或缓冲区类型之一。接收到的类型对象

标签: javascriptnode.jshttp

解决方案


我不确定您是否正确使用了流。尝试这个:

fs.createReadStream(filePath).pipe(req);

推荐阅读