'How can you upload files as a []byte in go?

I would like to use golang post request, upload pictures, but I do not want to pass filepath, just want to pass [] byte The following article are not what I need because they are used os.Open golang POST data using the Content-Type multipart/form-data

func Upload(url, file string) (err error) {
    // Prepare a form that you will submit to that URL.
    var b bytes.Buffer
    w := multipart.NewWriter(&b)
    // Add your image file
    f, err := os.Open(file)
    if err != nil {
        return 
    }
    defer f.Close()
    fw, err := w.CreateFormFile("image", file)
    if err != nil {
        return 
    }
    if _, err = io.Copy(fw, f); err != nil {
        return
    }
    // Add the other fields
    if fw, err = w.CreateFormField("key"); err != nil {
        return
    }
    if _, err = fw.Write([]byte("KEY")); err != nil {
        return
    }
    // Don't forget to close the multipart writer.
    // If you don't close it, your request will be missing the terminating boundary.
    w.Close()

    // Now that you have a form, you can submit it to your handler.
    req, err := http.NewRequest("POST", url, &b)
    if err != nil {
        return 
    }
    // Don't forget to set the content type, this will contain the boundary.
    req.Header.Set("Content-Type", w.FormDataContentType())

    // Submit the request
    client := &http.Client{}
    res, err := client.Do(req)
    if err != nil {
        return 
    }

    // Check the response
    if res.StatusCode != http.StatusOK {
        err = fmt.Errorf("bad status: %s", res.Status)
    }
    return
}


Solution 1:[1]

Since you use

if _, err = io.Copy(fw, f); err != nil {
    return
}

You may as well edit your code to:

  1. Add new import: "bytes"
  2. Change the method signature to func Upload(url string, file []byte) (err error)
  3. Use io.Copy(fw, bytes.NewReader(f))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Artur