2014-01-15 06:33
浏览 244


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

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.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试上传一个文件,该文件需要我为API设置特定的Content-Type。 当我这样做时:

 文件,err:= os.Open(“ helloWorld.wav”)
buf:= new(bytes.Buffer)
writer:=多部分。  NewWriter(buf)
audioFile,_:= writer.CreateFormFile(“ file”,“ helloWorld.wav”)
_,err = io.Copy(audioFile,file)
if err!= nil {
返回nil,0  ,err 

它会正确创建多部分表单,但假定该内容类型为: < pre> 内容类型:application / octet-stream

我需要将其设置为: < pre> Content-Type:audio / wav; rate = 8000

虽然我当然可以为net / http设置标题,但我没有看到 如何以多部分形式对单个字段执行此操作。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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)


    --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.

    解决 无用
    打赏 举报

相关推荐 更多相似问题