I
I
Ilya2015-04-21 20:03:37
go
Ilya, 2015-04-21 20:03:37

How to upload photos to the wall in vk.com using golang?

How do I post a message with a photo on a community page? There was a problem with uploading photos to the VK server. I get the URI for uploading normally through photos.getWallUploadServer, but when I try to upload, then nothing. Here is the download code:

file, err := os.Open(path)
body := &bytes.Buffer{}
  writer := multipart.NewWriter(body)
  part, err := writer.CreateFormFile("photo", filepath.Base(path))
_, err = io.Copy(part, file)
req, err := http.NewRequest("POST", uri, body) //урл, который я получил
client.Do(req)

But it gives me back
{
"server":624716,
"photo":"[]",
"hash":"170a83ae98131138eabde22ca0b3013f"
}

Please explain where I'm wrong.
Ps All rights reserved.
UPD:
So far I'm working like this:
file, err := os.Open(path)
  defer file.Close()

  body := &bytes.Buffer{}
  writer := multipart.NewWriter(body)
  part, err := writer.CreateFormFile(paramName, filepath.Base(path))
  _, err = io.Copy(part, file)
  err = writer.Close()

  resp, _ := http.DefaultClient.Post(uri, writer.FormDataContentType(), body)
  defer resp.Body.Close()
  response_body, err := ioutil.ReadAll(resp.Body)

But I began to eat more memory.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex, 2015-05-01
@alehano

Here is my function. I'm passing io.Reader instead of a file, but it's basically the same as yours.

func postImg(url string, img io.Reader) (server int, photo, hash string, err error) {
  type UploadResponse struct {
    Server int    `json:"server"`
    Photo  string `json:"photo"`
    Hash   string `json:"hash"`
  }

  var b bytes.Buffer
  w := multipart.NewWriter(&b)
  fw, err := w.CreateFormFile("photo", "photo.jpg")
  if err != nil {
    return
  }
  if _, err = io.Copy(fw, img); err != nil {
    return
  }
  w.Close()

  req, err := http.NewRequest("POST", url, &b)
  if err != nil {
    return
  }
  req.Header.Set("Content-Type", w.FormDataContentType())

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

  // resp
  uplRes := UploadResponse{}
  dec := json.NewDecoder(res.Body)
  err = dec.Decode(&uplRes)
  if err != nil {
    return
  }
  defer res.Body.Close()

  server = uplRes.Server
  photo = uplRes.Photo
  hash = uplRes.Hash
  return
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question