RESTful uploading of a file in PHP

2019-05-10 22:28发布

So I'm working on a script that's going to upload a video to a server via a RESTful interface. The documentation tells me that I should pass the data (including the binary video file) as part of a POST request. I know how to set my POST variables, but I'm not sure how to do the binary data. The API says I should have a field called 'media' and it should contain the raw video data.

So let's say I have a video called 'video1.mp4' and I want to include its contents in my 'media' POST variable. How can I do this?

Thanks!

标签: php api rest
1条回答
乱世女痞
2楼-- · 2019-05-10 22:57

I don't know how you're communication with the API, but I'll assume cURL for this example. To send files, you use the CURLOPT_POSTFIELDS option:

CURLOPT_POSTFIELDS
The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.

With an example further down on the page:

$ch = curl_init();

$data = array('name' => 'Foo', 'media' => '@/home/user/test.png');

curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

curl_exec($ch);
查看更多
登录 后发表回答