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.

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

报告相同问题?

悬赏问题

  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥15 QT6颜色选择对话框显示不完整
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥15 DS18B20内部ADC模数转换器