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

Patricia Arquette
Release: 2024-10-28 08:01:02
Original
660 people have browsed it

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

Customizing Content-Type for Multipart Form Fields in Go

Sending multipart forms often requires specifying a specific Content-Type header for individual fields, such as when uploading an audio file. While Go's multipart/mime package provides a convenient way to create multipart forms, it doesn't allow for setting field-specific Content-Type headers.

Solution

As there is currently no built-in support for this functionality, a custom solution can be implemented. Here's a modified version of the CreateFormFile function:

<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>
Copy after login

Usage

To use this custom function:

<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>
Copy after login

Output

This will generate a multipart form with the following metadata:

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

This way, you can easily set the Content-Type for specific form fields when using the multipart/mime package.

The above is the detailed content of How to Customize Content-Type for Multipart Form Fields in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!