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

Barbara Streisand
Release: 2024-11-04 05:39:30
Original
364 people have browsed it

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>
    Copy after login
  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>
    Copy after login
  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>
    Copy after login
  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>
    Copy after login
  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>
    Copy after login
  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>
    Copy after login
  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>
    Copy after login
  8. Read Response:

    Read the response body:

    <code class="go">cnt, err := io.ReadAll(res.Body)
    if err != nil {
        return []byte{}, err
    }</code>
    Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!