Multipart requests are frequently used for file uploads, where along with the file, additional form data needs to be submitted. Let's look at how we can tackle this using Go's mime/multipart and http packages.
Consider the following HTML form:
<form action="/multipart" enctype="multipart/form-data" method="POST"> <label for="file">Please select a File</label> <input>
In Go, we can send this multipart request as follows:
import ( "bytes" "io" "mime/multipart" "net/http" ) var buffer bytes.Buffer w := multipart.NewWriter(&buffer) // Write form fields w.CreateFormField("input1") w.WriteField("input1", "value1") // Prepare to write a file fd, err := os.Open("filename.dat") if err != nil { return err } // Create a form field for the file fw, err := w.CreateFormFile("file", fd.Name()) if err != nil { return err } // Copy file contents into form field if _, err := io.Copy(fw, fd); err != nil { return err } // Close writer w.Close() // Prepare request resp, err := http.Post(url, w.FormDataContentType(), &buffer) if err != nil { return err }
The key to sending files in multipart requests lies in using CreateFormFile on the *multipart.Writer to create a form field specifically for the file. Once created, we can use io.Copy to write the file's contents into this form field.
The above is the detailed content of How do I POST Files and Form Data Using Go\'s `multipart/form-data`?. For more information, please follow other related articles on the PHP Chinese website!