Home >Backend Development >Golang >How to Send Multipart Forms with Files Using Go\'s `mime/multipart` and `net/http` Packages?
This guide provides a solution to sending multipart forms using Go packages mime/multipart and http.
Consider the following HTML markup:
<html> <head><title>Multipart Test</title></head> <body> <form action="/multipart" enctype="multipart/form-data" method="POST"> <label for="file"> Please select a File </label> <input>
For the Go implementation:
import ( "bytes" "io" "mime/multipart" "net/http" "os" ) // Upload file to google code func Upload(tarball string) (err os.Error) { // Create buffer buf := new(bytes.Buffer) // caveat IMO dont use this for large files, \ // create a tmpfile and assemble your multipart from there (not tested) w := multipart.NewWriter(buf) // Create a form field writer for field label label, err := w.CreateFormField("label") if err != nil { return err } // Write label field label.Write([]byte("label here")) // Create a form field writer for field summary summary, err := w.CreateFormField("summary") if err != nil { return err } // Write summary field summary.Write([]byte("summary here")) // Create file field fw, err := w.CreateFormFile("upload", tarball) if err != nil { return err } fd, err := os.Open(tarball) if err != nil { return err } defer fd.Close() // Write file field from file to upload _, err = io.Copy(fw, fd) if err != nil { return err } // Important if you do not close the multipart writer you will not have a // terminating boundry w.Close() req, err := http.NewRequest("POST", repoUrl, buf) if err != nil { return err } req.Header.Set("Content-Type", w.FormDataContentType()) req.SetBasicAuth("[email protected]", "password") res, err := client.Do(req) if err != nil { return err } io.Copy(os.Stderr, res.Body) // Replace this with Status.Code check return err }
The above is the detailed content of How to Send Multipart Forms with Files Using Go\'s `mime/multipart` and `net/http` Packages?. For more information, please follow other related articles on the PHP Chinese website!