使用 application/octet-stream 内容类型发出 HTTP 请求 - Node js

Ign*_*ška 4 file-upload node.js

目前我正在使用 npm 模块请求上传具有 application/octet-stream 内容类型的文件。问题是我无法取回响应正文。这是由于已知错误而发生的:https ://github.com/request/request/issues/3108

您能否提供一种将文件上传到具有应用程序/八位字节流内容类型的 API 的替代方法?

Ter*_*nox 8

您是否尝试过将文件加载到缓冲区而不是流中?我意识到在许多情况下流是更好的选择,但通常只需加载到内存中就可以接受。我使用这种方法没有任何问题:

const imageBuffer = fs.readFileSync(fileName); // Set filename here..

const options = {
    uri: url, /* Set url here. */
    body: imageBuffer,
    headers: {
        'Content-Type': 'application/octet-stream'
    }
};


request.post(options, (error, response, body) => {
if (error) {
    console.log('Error: ', error);
    return;
}
Run Code Online (Sandbox Code Playgroud)

使用流来做同样的事情:

const options = {
    uri: url, /* Set url here. */
    body: fs.createReadStream(fileName),
    headers: {
        'Content-Type': 'application/octet-stream'
    }
};

request.post(options, (error, response, body) => {
if (error) {
    console.log('Error: ', error);
    return;
}
..
Run Code Online (Sandbox Code Playgroud)