I
I
impressive172020-10-10 16:53:09
go
impressive17, 2020-10-10 16:53:09

How to make post request with base64 image in Golang?

I have a regular jpg image in the root of the project. I need to make a post request with this image in base64 to a specific url. The request body should be something like:
"image": {
"base64": '"`base64 ./My-image.jpeg`"'"
}
How can I do this?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sotanodroid, 2020-10-10
@impressive17

package main

import (
  "encoding/json"
    "bufio"
    "encoding/base64"
    "io/ioutil"
  "os"
)

type imageJSON struct {
  Base64 string `json:"base64"`
}

func main() {
    // Открыть файл
    f, _ := os.Open("./myimage.jpg")

    // сканируем содержимое
    reader := bufio.NewReader(f)
    content, _ := ioutil.ReadAll(reader)

    // кодируем в base64
  encoded := base64.StdEncoding.EncodeToString(content)
  data := imageJSON{
    Base64: encoded,
  }
  payload, _ := json.Marshal(data)
  println(string(payload))
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question