douhe8981 2014-01-15 06:33
浏览 380
已采纳

如何在Go中使用'multipart'设置表单的Content-Type

I am attempting to upload a file that requires me to set a specific Content-Type for the API. When I do this:

file, err := os.Open("helloWorld.wav")
buf := new(bytes.Buffer)
writer := multipart.NewWriter(buf)
audioFile, _ := writer.CreateFormFile("file", "helloWorld.wav")
_, err = io.Copy(audioFile, file)
if err != nil {
     return nil, 0, err
}
writer.Close()

It creates the multipart form properly, but assumes this content type:

Content-Type: application/octet-stream

I need to be able to set it to:

Content-Type: audio/wav;rate=8000

While of course I may set the headers for net/http, I am not seeing how to do this for individual fields in a multipart form.

  • 写回答

1条回答 默认 最新

  • doumouyi4039 2014-01-15 09:11
    关注

    Looking at the source code mime/multipart it's not possible, but you could implement something like this (note: it's not handling the escaping of filename correctly)

        func CreateAudioFormFile(w *multipart.Writer, filename string) (io.Writer, error) {
          h := make(textproto.MIMEHeader)
          h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, "file", filename))
          h.Set("Content-Type", "audio/wav;rate=8000")
          return w.CreatePart(h)
    }
    

    Outputs

    --0c4c6b408a5a8bf7a37060e54f4febd6083fd6758fd4b3975c4e2ea93732 Content-Disposition: form-data; name="file"; filename="helloWorld.wav" Content-Type: audio/wav;rate=8000 --0c4c6b408a5a8bf7a37060e54f4febd6083fd6758fd4b3975c4e2ea93732--

    See playground for full example.

    Edit: To write the file data, also copy it to the writer as in the original example.

    audioFile, _ := CreateAudioFormFile(writer2, "helloWorld.wav")
    io.Copy(audioFile, file)
    

    See updated playground for the full example that includes the file data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器