【问题标题】:How to set Content-Type for a form filed using 'multipart' in Go如何在 Go 中为使用“multipart”提交的表单设置 Content-Type
【发布时间】:2014-01-16 08:31:53
【问题描述】:

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

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()

它正确地创建了多部分表单,但假定了这种内容类型:

Content-Type: application/octet-stream

我需要能够将其设置为:

Content-Type: audio/wav;rate=8000

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

【问题讨论】:

    标签: go multipartform-data


    【解决方案1】:

    查看源代码mime/multipart 是不可能的,但你可以实现这样的东西(注意:它没有正确处理文件名的转义)

        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 内容处置:表单数据;名称=“文件”;文件名="helloWorld.wav" 内容类型:音频/wav;速率=8000 --0c4c6b408a5a8bf7a37060e54f4febd6083fd6758fd4b3975c4e2ea93732--

    完整示例请参见playground

    编辑:要写入文件数据,也像原始示例一样将其复制到写入器。

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

    有关包含文件数据的完整示例,请参阅 updated playground

    【讨论】:

    • 这很适合设置字段。但我不清楚如何使用 net/textproto 在新创建的字段中添加文件内容。
    • 更新了细节,和你最初做的完全一样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-13
    • 2021-08-28
    • 2018-01-26
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多