如何使用Guzzle上传文件(OAuth 2)

时间:2015-12-04 08:54:24

标签: php curl laravel-5.1 guzzle box

我正在尝试使用Guzzle HTTP客户端上传文件并将其发送到API URL。但是,我无法在此获得成功。我可以使用Curl,但我想使用Guzzle。我无法弄清楚用Guzzle添加上传文件的位置以及如何使用属性。这是相关的Curl代码:

curl https://upload.box.com/api/2.0/files/content \
  -H "Authorization: Bearer ACCESS_TOKEN" -X POST \
  -F attributes='{"name":"tigers.jpeg", "parent":{"id":"11446498"}}' \
  -F file=@myfile.jpg

以下是我希望您会发现有用的参考API文档。我正在使用Laravel 5。

无论我每次做什么,我都会得到Method not allowed回复。这是我正在尝试的以下代码:

$client = new Client();
        $sendRequest = $client->post('https://upload.box.com/api/2.0/files/content', [], [
            'request.options' => [
                'headers' => [
                    'Authorization' => 'Bearer ' . $access_token
                ]
            ],
            'file' => '/picture.jpg'
        ]);
        $sendRequest->setBody('{"attributes": {"name": "picture.jpg", "parent": {"id": "5605448193"}}}');
try {
    $response = $sendRequest->send();
    dd($response);
} catch(BadResponseException $e) {
        dd($e->getResponse());
    }

1 个答案:

答案 0 :(得分:1)

我自己已经弄清楚了。以下是相关代码(完整的Controller方法),希望您在一天内可以找到它们:

public function store(Request $request)
    {
        if ($request->hasFile('file')) {
            $api = Api::latest()->take(1)->get();
            $access_token = $api[0]->access_token;
            if(Auth::user()->role == 'Administrator') {
                $folder_id = $request->input('folder_id');
            } elseif(Auth::user()->role == 'Subscriber') {
                $folder_id = Auth::user()->folder_id;
            }
            $client = new Client();
            $apiRequest = $client->post('https://upload.box.com/api/2.0/files/content');
            $apiRequest->setHeaders([
                'Authorization' => 'Bearer ' . $access_token,
                'Content-Type' => 'multipart/form-data'
            ]);
            $apiRequest->setPostField('filename', $request->file('file')->getClientOriginalName());
            $apiRequest->setPostField('parent_id', $folder_id);
            $apiRequest->addPostFile(
                'file', $request->file('file')->getRealPath(),
                $request->file('file')->getClientMimeType(),
                $request->file('file')->getClientOriginalName()
            );
            try {
                $sendRequest = $apiRequest->send();
                if ($sendRequest->isSuccessful()) {
                    return redirect()->back()->with('fileUpload', trans('Your file has been uploaded successfully'));
                }
            } catch (BadResponseException $e) {
                $result = $e->getResponse()->getStatusCode();
                if ($result === 401) {
                    $this->regenerate_access_token();
                    $api = Api::latest()->take(1)->get();
                    $access_token = $api[0]->access_token;
                    $client = new Client();
                    $apiRequest = $client->post('https://upload.box.com/api/2.0/files/content');
                    $apiRequest->setHeaders([
                        'Authorization' => 'Bearer ' . $access_token,
                        'Content-Type' => 'multipart/form-data'
                    ]);
                    $apiRequest->setPostField('filename', $request->file('file')->getClientOriginalName());
                    $apiRequest->setPostField('parent_id', Auth::user()->folder_id);
                    $apiRequest->addPostFile(
                        'file', $request->file('file')->getRealPath(),
                        $request->file('file')->getClientMimeType(),
                        $request->file('file')->getClientOriginalName()
                    );
                    $sendRequest = $apiRequest->send();
                    if ($sendRequest->isSuccessful()) {
                        return redirect()->back()->with('fileUpload', trans('Your file has been uploaded successfully'));
                    }
                } elseif ($result === 409) {
                    return redirect()->back()->with('fileUpload', trans('You have already a file with the same name. Please, rename your file to successful upload'));
                }
            }
        } else {
            return redirect()->back()->with('fileUpload', trans('Please, select a file to upload'));
        }
    }

以下是文件上传表单,该表单应位于view目录中:

<form action="/store" method="post" enctype="multipart/form-data">
    {{ csrf_field() }}

    <div class="row">
        @can('viewElements', \Illuminate\Support\Facades\Auth::user())
        <div class="input-field col s3">
            <select name="folder_id" id="folder_id">
                <option value="" disabled selected>Choose User</option>
                @foreach($users as $user)
                    <option value="{{ $user->folder_id }}">{{ $user->name }}</option>
                @endforeach
            </select>
        </div>
        @endcan

        <div class="col {{ $class }}">
            <div class="file-field input-field">
                <div class="btn">
                    <span>File</span>
                    <input type="file" name="file" required>
                </div>

                <div class="file-path-wrapper">
                    <input type="text" class="file-path validate" placeholder="Upload your file">
                </div>
            </div>
        </div>
        <div class="col s3">
            <button class="btn waves-effect waves-light" type="submit">Submit <i class="material-icons right">send</i></button>
        </div>
    </div>
</form>