Home > Backend Development > Golang > How to Handle Multipart Form Submissions in Go using `mime/multipart` and `http`?

How to Handle Multipart Form Submissions in Go using `mime/multipart` and `http`?

Patricia Arquette
Release: 2024-11-26 09:41:14
Original
786 people have browsed it

How to Handle Multipart Form Submissions in Go using `mime/multipart` and `http`?

Multipart Form Submission using Go Packagesmime/multipart and http

When creating a multipart form, you can use the mime/multipart and http packages in Go. A sample HTML form is provided here.

<form action="/multipart" enctype="multipart/form-data" method="POST">
  <label for="file">Please select a File </label>
  <input>
Copy after login

In Go, the following approach can be used:

var buffer bytes.Buffer
w := multipart.NewWriter(&buffer)
// Write fields and files
w.CreateFormField("input1")
w.WriteField("input1", "value1")
w.CreateFormFile("file", "filename.dat")
// Create a reader to read the file
resp, err := http.Post(url, w.FormDataContentType(), &buffer)
Copy after login

To retrieve the file, a Reader is required. Here's how it can be done:

// Upload file to google code
func Upload(tarball string) (err os.Error) {
    // ... (code omitted)
    // Create file field
    fw, err := w.CreateFormFile("upload", tarball)
    // ... (code omitted)
    // Write file field from file to upload
    _, err = io.Copy(fw, fd)
    // ... (code omitted)
    return err
}
Copy after login

This solution provides a comprehensive approach to submitting multipart forms in Go using the specified packages.

The above is the detailed content of How to Handle Multipart Form Submissions in Go using `mime/multipart` and `http`?. 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