作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想使用 google-api-php-client 以外的 php curl 上传,但我真的不知道该怎么做,这里是文档:Send a multipart upload request
这是我的代码片段,我卡在 CURLOPT_POSTFIELDS
中,有人可以帮我解决这个问题吗?
public function uploadByCurl($uploadFilePath, $accessToken){
$ch = curl_init();
$mimeType = $this->getMimeType($uploadFilePath);
$options = [
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => [
'file' => new \CURLFile($uploadFilePath),
// 'name' =>
],
CURLOPT_HTTPHEADER => [
'Authorization:Bearer ' . $accessToken,
'Content-Type:' . $mimeType,
'Content-Length:' . filesize($uploadFilePath),
],
//In case you're in Windows, sometimes will throw error if not set SSL verification to false
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
];
//In case you need a proxy
//$options[CURLOPT_PROXY] = 'http://127.0.0.1:1087';
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
return $result;
}
我只是不知道如何将其转化为代码(不熟悉multipart/related
):
最佳答案
multipart/ralated
和 Drive API v3 上传文件。如果我的理解是正确的,这个答案怎么样?
multipart/ralated
创建包含文件和元数据的结构并提出请求。当你的脚本修改后,变成如下。
public function uploadByCurl($uploadFilePath, $accessToken){
$handle = fopen($uploadFilePath, "rb");
$file = fread($handle, filesize($uploadFilePath));
fclose($handle);
$boundary = "xxxxxxxxxx";
$data = "--" . $boundary . "\r\n";
$data .= "Content-Type: application/json; charset=UTF-8\r\n\r\n";
$data .= "{\"name\": \"" . basename($uploadFilePath) . "\", \"mimeType\": \"" . mime_content_type($uploadFilePath) . "\"}\r\n";
$data .= "--" . $boundary . "\r\n";
$data .= "Content-Transfer-Encoding: base64\r\n\r\n";
$data .= base64_encode($file);
$data .= "\r\n--" . $boundary . "--";
$ch = curl_init();
$options = [
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart',
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => [
'Authorization:Bearer ' . $accessToken,
'Content-Type:multipart/related; boundary=' . $boundary,
],
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => 0,
];
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close ($ch);
return $result;
}
$uploadFilePath
中检索的。Multipart upload: uploadType=multipart. For quick transfer of a small file (5 MB or less) and metadata that describes the file, all in a single request.
关于php - 如何使用 php-curl 将文件上传到 "multipart"类型的 Google 云端硬盘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60813750/
我是一名优秀的程序员,十分优秀!