E
E
EvgMul2016-08-15 14:40:41
PHP
EvgMul, 2016-08-15 14:40:41

How to correctly upload images through the VKontakte API?

Hello. Please help me with the following issue. You need to upload a photo to the group's album via the VK API. I got to the point of getting the URL for uploading a photo, and then I do the following:

//Получили URL для загрузки
$uploadUrl = $result->response->upload_url;
//Путь до картинки. Тут у меня еще есть вопрос, а можно ли использовать пути типа http://example.com/test/image.jpg ? Хотя это не важно на данный момент
$file_path = "images/2.jpg";
$postParam = array("file1"=> "@".$file_path);
$ch = curl_init($uploadUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postParam);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data; charset=UTF-8'));
$json = json_decode(curl_exec($ch));
curl_close($ch);

As a result, I get the following response:
stdClass Object
(
    [server] => 630830
    [photos_list] => []
    [aid] => 234908050
    [hash] => a14bbef18e6d15798955f9a4ba59a77e
    [gid] => 126877620
)

Can you please tell me where and what am I doing wrong that the Photos_list field returns empty?
Thanks in advance to all who respond.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
EvgMul, 2016-08-15
@EvgMul

With grief in half figured out what was the problem.
The point is that using curl_setopt ( $ch, CURLOPT_POSTFIELDS, array( 'file1' => '@' . $file ) );
since version 5.5. undesirable. On my server is 5.6.
Instead of this line, you should use

curl_setopt($ch, CURLOPT_POSTFIELDS, ['file1' => new CurlFile($file_path)]);

D
Dmitry, 2016-08-15
@slo_nik

Good afternoon.
First, check out the following code.

$file_path = "images/2.jpg";
$postParam = array("file1"=> "@".$file_path);

If you display in the browser,
will you get an image or not?
There may be a problem with the file path.
ps This, I think, is superfluous.
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data; charset=UTF-8'));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question