Answer the question
In order to leave comments, you need to log in
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)
{
"server":624716,
"photo":"[]",
"hash":"170a83ae98131138eabde22ca0b3013f"
}
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)
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question