php - 在 PHP 中以 RESTful 方式上传文件

标签 php api rest

所以我正在编写一个脚本,该脚本将通过 RESTful 接口(interface)将视频上传到服务器。文档告诉我应该将数据(包括二进制视频文件)作为 POST 请求的一部分传递。我知道如何设置我的 POST 变量,但我不确定如何设置二进制数据。 API 说我应该有一个名为“媒体”的字段,它应该包含原始视频数据。

假设我有一个名为“video1.mp4”的视频,我想将其内容包含在我的“媒体”POST 变量中。我该怎么做?

谢谢!

最佳答案

我不知道您是如何与 API 通信的,但我将假设此示例使用 cURL。要发送文件,您可以使用 CURLOPT_POSTFIELDS选项:

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.

在页面下方有一个示例:

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

关于php - 在 PHP 中以 RESTful 方式上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3192496/

相关文章:

javascript - 如何使用通用方法通过重用代码来定义 React 组件

java - 有限的SortedSet

rest - Angular2 Http/Jsonp 不发出请求

node.js - 使用 firebase admin sdk 进行 REST api 身份验证

php - 亚马逊 MWS Scratchpad API

php - Regex量化捕获

php - 从 Linux 命令行检查有效的 docx

php - CSS 不适用于 PHP MYSQL 中带有子菜单的菜单

node.js - 使用 ng 服务器 Angular 6 运行脚本

json - 如何为所有 API 端点全局设置 http.ResponseWriter Content-Type header ?