Nodejs:将流上传到form-data会导致411 ‘Length-required’错误。

huangapple go评论53阅读模式
英文:

Nodejs: Uploading a stream to form-data results in 411 'Length-required'

问题

我正在尝试将文件上传到Storyblock API。这在幕后使用S3。本地文件上传可行,但尝试从外部URL获取文件时出现411错误。

这段代码可行:

import { createReadStream } from 'fs'
import FormData from 'form-data'

const form = new FormData()
form.append('file', createReadStream('./local-file.jpg))
form.submit(...)

但是,尝试对同一文件使用外部URL时不行:

import FormData from 'form-data'
import got, { type Got } from 'got'

const form = new FormData()
form.append('file', got.stream(externalUrl, {decompress: false})
form.submit(...)

响应:

  statusCode: 411,
  statusMessage: 'Length Required',

这表明,一些原因使得 got.stream() 输出的流与 createReadStream() 不同。

英文:

I'm trying to upload a file to the storyblock API. This uses S3 behind the scenes. Local file uploads work, but when trying to fetch a file from an external URL I get a 411 error.

This works:

    import { createReadStream } from 'fs'
    import FormData from 'form-data'
    
    const form = new FormData()
    form.append('file', createReadStream('./local-file.jpg))
    form.submit(...)

But when trying an external URL for the same file it doesn't:

    import FormData from 'form-data'
    import got, { type Got } from 'got'
    
    const form = new FormData()
    form.append('file', got.stream(externalUrl, {decompress: false})
    form.submit(...)

Response:

  statusCode: 411,
  statusMessage: 'Length Required',

Which indicates that somehow got.stream() gives a different stream output than createReadStream()

答案1

得分: 1

Content-Length 头部缺失,这就是为什么会返回 411。需要确定要上传的文件大小,然后在请求中包括 Content-Length 头部。在提交之前添加以下代码:

// 获取文件大小
const { headers } = await got.head(externalUrl);
const contentLength = headers['content-length'];

// 使用正确的内容长度将文件附加到表单中
form.append('file', stream, { knownLength: contentLength });
英文:

Content-Length header is missing that is why it's giving you 411. The size of file being uploaded needs be determined and then include the Content-Length header in the request. Add this before submit.

// Get the file size
const { headers } = await got.head(externalUrl);
const contentLength = headers['content-length'];
    
// Append the file to the form with the correct content length
form.append('file', stream, { knownLength: contentLength });

huangapple
  • 本文由 发表于 2023年7月13日 21:02:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/76679671.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定