Home > Article > Backend Development > How to Upload a File with a POST Request in Go?
Upload a File with a POST Request in Go
Uploading a file via a POST request is a common task when developing web applications. This becomes even more important when working with Telegram bots, which require files to be uploaded as part of API calls.
Unfortunately, using a simple http.Post function may result in errors like "Bad Request: there is no photo in the request." To resolve this issue, you need to send the file using the multipart/form-data content type. Here's how you can achieve that:
Create a Content Structure:
Define a content struct to represent the file's metadata and data:
<code class="go">type content struct { fname string ftype string fdata []byte }</code>
Multipart Form Builder:
Use multipart.NewWriter to create a new multipart form builder:
<code class="go">var buf = new(bytes.Buffer) var w multipart.NewWriter(buf)</code>
Add File Data:
Iterate over the files you need to upload and create a form part for each one:
<code class="go">for _, f := range files { part, err := w.CreateFormFile(f.ftype, filepath.Base(f.fname)) if err != nil { return []byte{}, err } _, err = part.Write(f.fdata) if err != nil { return []byte{}, err } }</code>
Close Form:
Once you have added all files, close the multipart form builder:
<code class="go">err := w.Close() if err != nil { return []byte{}, err }</code>
Create HTTP Request:
Create a new HTTP request using http.NewRequest:
<code class="go">req, err := http.NewRequest("POST", url, buf) if err != nil { return []byte{}, err }</code>
Set Content Type:
Set the Content-Type header to indicate that you are sending multipart/form-data:
<code class="go">req.Header.Add("Content-Type", w.FormDataContentType())</code>
Send Request:
Send the HTTP request using an HTTP client:
<code class="go">client := &http.Client{} res, err := client.Do(req) if err != nil { return []byte{}, err }</code>
Read Response:
Read the response body:
<code class="go">cnt, err := io.ReadAll(res.Body) if err != nil { return []byte{}, err }</code>
By following these steps, you can successfully upload files with POST requests in Go, including when working with Telegram bots.
The above is the detailed content of How to Upload a File with a POST Request in Go?. For more information, please follow other related articles on the PHP Chinese website!