且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

RESTful 在 PHP 中上传文件

更新时间:2023-11-30 13:42:28

我不知道你是如何与 API 通信的,但我会假设这个例子是 cURL.要发送文件,您可以使用 CURLOPT_POSTFIELDS选项:

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
要在 HTTPPOST"操作中发布的完整数据.要发布文件,请在文件名前加上 @ 并使用完整路径.这可以作为 urlencoded 字符串(如 'para1=val1&para2=val2&...')或作为以字段名称作为键和字段数据作为值的数组传递.如果 value 是数组,则 Content-Type 标头将设置为 multipart/form-data.

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);