使用 Laravel 将文件上传到 Dropbox 意外地将元数据添加到文件内容

时间:2021-04-26 09:34:19

标签: laravel dropbox dropbox-api

我很想使用 Laravel Http 客户端将文件(图像/文本)上传到我的保管箱。

我的代码:

$params = [ "path"=> "/TEST/sometext.txt",
            "mode"=> "add",
            "autorename"=> true,
            "mute"=> false,
            "strict_conflict"=> false];

$address = 'https://content.dropboxapi.com/2/files/upload';
$response = Http::attach( 'attachment', fopen(public_path().'/img/text.txt','r'), 'text.txt')
            ->withHeaders(['Authorization' => 'Bearer SOMEKEYS',
            'Content-Type' => 'application/octet-stream',
            'Dropbox-API-Arg'=>json_encode($params)
            ])
            ->post($address);

            dd($response->body());

它发送成功,但文件( .txt )的内容更新了一些“元数据”

原始文件:

some text dont edit..

文件上传到 Dropbox:

--71df864b515ecbb345df5a9496afd21bb03093e0
Content-Disposition: form-data; name="attachment"; filename="text.txt"
Content-Length: 23
Content-Type: text/plain

some text dont edit..

--71df864b515ecbb345df5a9496afd21bb03093e0--

也许这与我上传图片的原因相同..它已损坏..我做错了什么..非常感谢!

1 个答案:

答案 0 :(得分:1)

我通过不使用 Laravel 的 http 客户端解决了这个问题..我只是使用了裸露的 php curl 请求..

$params = [ "path"=> "/TEST/background.jpg",
                        "mode"=> "add",
                        "autorename"=> true,
                        "mute"=> false,
                        "strict_conflict"=> false];
                        

            //The URL you're sending the request to.
            $url = 'https://content.dropboxapi.com/2/files/upload';

            //Create a cURL handle.
            $ch = curl_init($url);

            //Create an array of custom headers.
            $customHeaders = array(
                 'Authorization: Bearer xxxx',
                 'Content-Type: application/octet-stream',
                 'Dropbox-API-Arg: '.json_encode($params)
            );

            //Use the CURLOPT_HTTPHEADER option to use our
            //custom headers.
            curl_setopt($ch, CURLOPT_HTTPHEADER, $customHeaders);

            //Set options to follow redirects and return output
            //as a string.
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents(public_path().'/img/background.jpg'));

            //Execute the request.
            $result = curl_exec($ch);
相关问题