【问题标题】:Send file with form-data and axios使用表单数据和 axios 发送文件
【发布时间】:2020-11-14 19:28:48
【问题描述】:

我正在尝试将视频发送到视频网站,我可以使用 REST api 和邮递员上传视频,所以我知道 api 可以按预期工作。现在我想使用 axios 做同样的请求。我的代码类似于如何使用表单数据和 axios 的示例:

const form = new FormData();
const stream = fs.createReadStream(PATH_TO_FILE);

form.append('image', stream);

// In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders`
const formHeaders = form.getHeaders();

axios.post('http://example.com', form, {
  headers: {
    ...formHeaders,
  },
})
.then(response => response)
.catch(error => error)

我收到data: 'Content-Length is required'的错误

有什么想法吗?

【问题讨论】:

标签: javascript node.js axios form-data


【解决方案1】:

可能是我把你的问题弄错了,你想在标题中添加 Content-Length。 我可以看到您正在上传视频流。所以首先你要计算数据块的长度。

('Content-Length', File.getSize(stream)) 参考:Can I stream a file upload to S3 without a content-length header?

您可以将发布请求设为多部分类型:'Content-Type': 'multipart/form-data'。 将大数据发送到服务器的首选方式。 您可以查看此链接:How do I set multipart in axios with react?

如果我的问题有误,请评论或回复。谢谢

【讨论】:

  • 谢谢!您的评论帮助我找到了解决方案!解决方案见下文:Content-Length": fs.statSync(filePath)['size']
  • 请标记为重复而不是解释现有答案。
【解决方案2】:

我的问题的解决方案是相应地设置 Content-Length:

"Content-Length": fs.statSync(filePath)['size']

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 2020-03-05
    • 2020-11-21
    • 2021-10-20
    • 2019-04-23
    • 2021-12-09
    • 1970-01-01
    • 2020-06-05
    相关资源
    最近更新 更多