我无法在golang中为特定的多部分部分添加标题。

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

I can't add a Header to a specific multipart part in golang

问题

我正在使用一个需要多部分表单的内容类型为Content-Type: audio/wav的API,但是如果你添加一个文件,使用part, _ := writer.CreateFormFile("audio_file", "test2.wav"),它会将内容类型设置为application/octet-stream。

我尝试过:
part.Header.Set("Content-Type", "audio/wav")
但是Header未定义。

这是一个可行的curl请求数据,不包含二进制数据:

Content-Disposition: form-data; name="audio_file"; filename="test2.wav"
Content-Type: audio/wav

这是一个被拒绝的请求,不包含二进制数据:

Content-Disposition: form-data; name="audio_file"; filename="test2.wav"
Content-Type: application/octet-stream
英文:

I'm using an API that requires the content-type of a multipart form to be Content-Type: audio/wav but if you add a file with
part, _ := writer.CreateFormFile("audio_file", "test2.wav")
it makes the content-type application/octet-stream

I've tried:
part.Header.Set("Content-Type", "audio/wav")
but Header is undefined.

Here is the curl request data minus the binary that works:

Content-Disposition: form-data; name="audio_file"; filename="test2.wav"
Content-Type: audio/wav

Here is my request minus the binary data that is rejected:

Content-Disposition: form-data; name="audio_file"; filename="test2.wav"
Content-Type: application/octet-stream

答案1

得分: 3

直接调用CreatePart方法,而不是使用CreateFormFile便捷方法。在用于创建部分的标头中设置内容类型。

h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
    fmt.Sprintf(`form-data; name="%s"; filename="%s"`, "audio_file", "test2.wav"))
h.Set("Content-Type", "audio/wav")
part, err := writer.CreatePart(h)
英文:

Call CreatePart directly instead of the CreateFormFile convenience method. Set the content type in the header used to create the part.

h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
	fmt.Sprintf(`form-data; name="%s"; filename="%s"`, "audio_file", "test2.wav"))
h.Set("Content-Type", "audio/wav")
part, err := writer.CreatePart(h)

huangapple
  • 本文由 发表于 2022年12月17日 13:31:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/74832003.html
匿名

发表评论

匿名网友

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

确定