Problem:
How to perform a Pre-signed POST upload to upload files to an AWS S3 bucket using Go, without using the traditional Pre-signed PUT method?
Solution:
To perform a Pre-signed POST upload, follow these steps:
Construct and POST Multipart Form Data: Create a multipart form data request with the following fields:
Example Code in Go:
import ( "bytes" "fmt" "io" "mime/multipart" "net/http" "strings" ) // Fields represents the fields to be uploaded in the multipart form data request. type Fields struct { Key, Value string } // Upload performs a Pre-signed POST upload using the provided URL and fields. func Upload(url string, fields []Fields) error { var b bytes.Buffer w := multipart.NewWriter(&b) for _, f := range fields { fw, err := w.CreateFormField(f.Key) if err != nil { return err } if _, err := io.WriteString(fw, f.Value); err != nil { return err } } w.Close() req, err := http.NewRequest("POST", url, &b) if err != nil { return err } req.Header.Set("Content-Type", w.FormDataContentType()) client := &http.Client{} res, err := client.Do(req) if err != nil { return err } if res.StatusCode != http.StatusOK { err = fmt.Errorf("bad status: %s", res.Status) } return nil }
The above is the detailed content of How to Achieve Pre-signed POST File Uploads to AWS S3 using Go?. For more information, please follow other related articles on the PHP Chinese website!