首頁  >  文章  >  後端開發  >  如何在 Go 中自訂多部分錶單欄位的內容類型?

如何在 Go 中自訂多部分錶單欄位的內容類型?

Patricia Arquette
Patricia Arquette原創
2024-10-28 08:01:02665瀏覽

How to Customize Content-Type for Multipart Form Fields in Go?

在Go 中自訂多部分錶單欄位的Content-Type

傳送多部分錶單通常需要為各個欄位指定特定的Content -Type 標頭,例如上傳音訊檔案時。雖然 Go 的 multipart/mime 套件提供了一種建立多部分錶單的便利方法,但它不允許設定特定於欄位的 Content-Type 標頭。

解決方案

As目前沒有對此功能的內建支持,可以實施自訂解決方案。以下是CreateFormFile 函數的修改版本:

<code class="go">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)
}</code>

用法

要使用此自訂函數:

<code class="go">// Get file as bytes
file, err := os.Open("helloWorld.wav")
buf := new(bytes.Buffer)
writer := multipart.NewWriter(buf)

// Create multipart form field with custom Content-Type header
audioFile, _ := CreateAudioFormFile(writer, "helloWorld.wav")

// Copy file data to multipart form field
io.Copy(audioFile, file)
writer.Close()</code>

輸出

這將產生一個包含以下元資料的多部分錶單:
--0c4c6b408a5a8bf7a37060e54f4febd6083fd6758fd4b3975c4e2ea93732
Content-Disposition: form-data; name="file"; filename="helloWorld.wav"
Content-Type: audio/wav;rate=8000
[file data]
--0c4c6b408a5a8bf7a37060e54f4febd6083fd6758fd4b3975c4e2ea93732--

這樣,您可以在使用multipart/mime 時輕鬆設定特定表單欄位的Content-Type包裹。

以上是如何在 Go 中自訂多部分錶單欄位的內容類型?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn