英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论