You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言中无法为Multipart表单部件设置指定Content-Type的问题

问题:Multipart表单audio_file部件的Content-Type设置异常

我调用的API要求Multipart表单中的audio_file部件必须指定Content-Type: audio/wav,但使用标准库的writer.CreateFormFile("audio_file", "test2.wav")添加文件时,该部件默认的Content-Type会被设为application/octet-stream,不符合API要求。尝试用part.Header.Set("Content-Type", "audio/wav")修改时,又遇到Header未定义的错误。

可行的请求头(不含二进制数据):

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

被API拒绝的请求头(不含二进制数据):

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

解决方案

问题出在CreateFormFile返回的part是io.Writer类型,没有暴露Header字段。要自定义Content-Type,需改用CreatePart方法手动构造部件头部:

import (
    "fmt"
    "io"
    "mime/multipart"
    "net/textproto"
    "os"
)

// 假设已创建multipart.Writer和对应http.Request
writer := multipart.NewWriter(body)

// 构造部件头部信息
disposition := fmt.Sprintf(`form-data; name="audio_file"; filename="test2.wav"`)
header := textproto.MIMEHeader{}
header.Set("Content-Disposition", disposition)
header.Set("Content-Type", "audio/wav")

// 创建带自定义头部的部件
part, err := writer.CreatePart(header)
if err != nil {
    // 自行处理错误逻辑
    panic(err)
}

// 读取本地音频文件并写入部件
audioFile, err := os.Open("test2.wav")
if err != nil {
    panic(err)
}
defer audioFile.Close()

_, err = io.Copy(part, audioFile)
if err != nil {
    panic(err)
}

// 完成表单写入
writer.Close()

这段代码通过手动构造MIME头部,直接指定Content-Type为audio/wav,绕过了CreateFormFile的默认设置,满足API的要求。


内容的提问来源于stack exchange,提问作者vinniyo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 10:55:15