编程语言
首页 > 编程语言> > php – Dropbox v2 API – 大文件上传

php – Dropbox v2 API – 大文件上传

作者:互联网

关于同一主题,我的previous question就是这个问题.简单的文件上传很简单.

 $headers = array("Authorization: Bearer dropbox_token",
                  'Content-Type: application/octet-stream',
                'Dropbox-API-Arg: {"path":"/path/file.ext",
                "mode":"add"}');

 $data = "I love Stackoverflow";
 $ch = curl_init('https://content.dropboxapi.com/2/files/upload/');
 curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);

 curl_setopt($ch,CURLOPT_POST,true);
 curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
 curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
 $response = curl_exec($ch);
 curl_close($ch);
 echo $response;

但是,当要保存的文件数据达到10兆字节时,这不是一个可行的选择.我以为我会简单地使用新的(ish)PHP curl_file_create.

$headers = array("Authorization: Bearer Dropbox token",
              'Content-Type: application/octet-stream',
              'Dropbox-API-Arg: {"path":"/path/bigfile.txt",
                                 "mode":"add"}');

$ch = curl_init('https://content.dropboxapi.com/2/files/upload/');
curl_setopt($ch,CURLOPT_HTTPHEADER,$headers);
$args['file'] = curl_file_create('/path/to/bigfile.txt');

curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$args);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;

但是,这不起作用. Dropbox API返回消息

Error in call to API function “files/upload”: Bad HTTP “Content-Type” header: “application/octet-stream; boundary=–… Expecting one of “application/octet-stream”, “text/plain; charset=dropbox-cors-hack

我非常感谢能告诉我这里可能出错的人.

解决方法:

看起来像curl_file_create将文件编码为多部分表单上传,这与您在与Dropbox API交谈时不是您想要的.

如果我理解正确,那么您要解决的问题是您不希望将整个文件内容加载到内存中.那正确吗?

如果是这样,请试一试. (抱歉,我没有对它进行过测试,所以它可能包含错误.)

$headers = array('Authorization: Bearer Dropbox token',
                 'Content-Type: application/octet-stream',
                 'Dropbox-API-Arg: {"path":"/path/bigfile.txt",
                                    "mode":"add"}');

$ch = curl_init('https://content.dropboxapi.com/2/files/upload');
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);

$path = '/path/to/bigfile.txt';
$fp = fopen($path, 'rb');
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($path));

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

curl_close($ch);
fclose($fp);

echo $response;

请注意,如果您要上传大文件,则可能还需要考虑/files/upload_session_start, etc..这允许你以块的形式上传,它支持大于150MB的文件(/ files / upload不支持).

标签:dropbox-api,php,curl
来源: https://codeday.me/bug/20191003/1849811.html