Home  >  Article  >  Backend Development  >  How to Upload a File with a POST Request in Go?

How to Upload a File with a POST Request in Go?

Barbara Streisand
Barbara StreisandOriginal
2024-11-04 05:39:30366browse

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:

  1. 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>
  2. 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>
  3. 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>
  4. 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>
  5. 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>
  6. 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>
  7. 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>
  8. 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!

Statement:
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