Search code examples
gogo-gin

Can I upload image to Imgur via Golang


I want upload image to Imgur via Golang(framework:Gin)

Like front-end[upload] > [golang] > [imgur] > [response] > [DB]

My Code:

 APIURL := "https://api.imgur.com/3/image"
 file, err := c.FormFile("FILE")
 if err != nil{
   panic(err)
 }
 fileOpen,err := file.Open()
 if err != nil{
   panic(err)
 }
 defer fileOpen.Close()
 req, _ := http.NewRequest("POST",APIURL,strings.NewReader("image="+file.Filename))
 req.Header.Add("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
 req.Header.Add("Authorization", "Bearer ---------------------------")
 req.Header.Add("Cache-Control", "no-cache")
 client := &http.Client{}
 res, _ := client.Do(req)
 defer res.Body.Close()
 body, _ := ioutil.ReadAll(res.Body)
 fmt.Println(res)
 fmt.Println(string(body))

It response "error":"No image data was sent to the upload api"


Solution

  • Try this upload function

    // image is any reader
    func upload(image io.Reader, token string) {
        var buf = new(bytes.Buffer)
        writer := multipart.NewWriter(buf)
    
        part, _ := writer.CreateFormFile("image", "dont care about name")
        io.Copy(part, image)
    
        writer.Close()
        req, _ := http.NewRequest("POST", "https://api.imgur.com/3/image", buf)
        req.Header.Set("Content-Type", writer.FormDataContentType())
        req.Header.Set("Authorization", "Bearer "+token)
    
        client := &http.Client{}
        res, _ := client.Do(req)
        defer res.Body.Close()
        b, _ := ioutil.ReadAll(res.Body)
        fmt.Println(string(b))
    }