使用字符串主体发送多部分表单



我已经看到了几乎所有与此相关的答案,建议在nodejs中使用FormData的一些变体来构建多部分表单。

我希望在不使用FormData库的情况下实现相同的功能,而只是使用请求头和请求体的字符串。

只有一个答案提示如何实现这一点,但解决方案在字符串负载上使用stringify函数,因此我不确定正确的stringized body应该是什么样子。

不管怎样,我已经走到这里了;

import { RequestOptions } from "http"
const path: 'url/'
const method: 'POST'
const body = `--BOUNDARY
nContent-Disposition: form-data; name="file"; filename="test.txt"
nContent-Type: text/plain
nThis is the content of the file
n--BOUNDARY
nContent-Disposition: form-data; name="form-field-one"
nexample1
n--BOUNDARY
nContent-Disposition: form-data; name="form-field-two"
nexample2
n--BOUNDARY--`
const headers = {
'content-type': 'multipart/form-data; boundary=BOUNDARY',
'content-length': String(Buffer.byteLength(body))
}
const options = {
path,
method,
headers,
body
}
const response = await execute(options)

我不能创建一个完全最小的复制,因为我不允许发布执行函数的内容,但是我可以描述我需要使用的函数签名(这就是为什么我需要使用这个字符串方法)。

对于它的价值,我认为函数只是简单地使用基本的内置nodejshttp库。

import { RequestOptions } from "http"
const execute = async (options: RequestOptions): Promise<any> => { ... }

我使用这个得到一个错误,但是由于函数的内部,这个错误根本没有帮助。

无论如何,我认为应该可以复制发送多部分表单(带有文件和表单字段),只使用POST请求的body和header,而不需要额外的库来转换body的数据。

我的字符串是一个成功的Postman请求多部分表单请求的修改输出。

有人能指出我做错了什么吗?

几点:

  • `...`中的每一行都以换行符结束,但下一行以n开始,这为提供了另一个换行符,导致不需要的空行。
  • 确实需要在标题和内容之间使用空行。
  • 行必须以CRLF结束,因此必须在每行的最后一个字符添加r

试试这个:

const body = `--BOUNDARYr
Content-Disposition: form-data; name="file"; filename="test.txt"r
Content-Type: text/plainr
r
This is the content of the filer
--BOUNDARYr
Content-Disposition: form-data; name="form-field-one"r
r
example1r
--BOUNDARYr
Content-Disposition: form-data; name="form-field-two"r
r
example2r
--BOUNDARY--`

最新更新