【问题标题】:How can I post multiple files in Laravel using Guzzle?如何使用 Guzzle 在 Laravel 中发布多个文件?
【发布时间】:2021-07-30 02:38:31
【问题描述】:

我正在尝试使用 JWT 将文件上传到外部服务器进行身份验证。我的表单如下所示:

<form action="{{ route('operations.photos-for-families.upload', [$operation, $current->index]) }}" method="POST" enctype='multipart/form-data'>
    <input type="file" name="photos[]" multiple="multiple">
    @csrf
    <input type="submit" value="submit">
</form>

我的路线是这样的:

    Route::post('{operation}/{index}/photos-for-families/upload', function (Request $request, string $operation, int $index) {
        if (!opExists($operation, $index) || !$request->has('photos') || empty($request->allFiles()))
            return back()->withErrors(['Oops. Sorry, something went wrong.']);

        $response = Http::attach('photos', $request->allFiles())
            ->post("https://cdn.mydomain.co.uk/gallery/{$operation}/{$index}/upload", [
                'token' => JWT::encode([
                    'iss' => 'https://mydomain.co.uk',
                    'aud' => 'https://cdn.mydomain.co.uk',
                    'iat' => time(),
                    'exp' => time() + 30, // 30 seconds expiration in-case of intercepts or re-use
                    'nbf' => time() - ((60 * 60) * 24),
                    'data' => [
                        'user_id' => Auth::user()->id,
                    ]
                ], 'MY_KEY')
            ]);

        var_dump($response);
    })->name('operations.photos-for-families.upload');

但是,我似乎无法在一个请求中发送多张照片。

InvalidArgumentException
无效的资源类型:数组

我正在阅读Documentation,但找不到如何附加多张照片。我知道我不验证文件的 MimeType,因为它正在开发中,一旦工作就会发生。

任何帮助表示赞赏。 cdn 服务器上的代码如下所示:

Route::post('/gallery/{operation}/{index}/upload', function (Request $request, string $operation, int $index) {

    if(!$request->has('token'))
        return redirect()->away('https://mydomain.co.uk');

    try {
        $access = JWT::decode($request->get('token'), 'MY_KEY', ['HS256']);

        if ($access->iss !== 'https://mydomain.co.uk' ||
            $access->aud !== 'https://cdn.mydomain.co.uk') {
            abort(404);
        }

        if ($access->nbf > time())
            return redirect()->away('https://mydomain.co.uk');

        if ($access->exp < time())
            return redirect()->away('https://mydomain.co.uk');

        $files = [];

        foreach ($request->allFiles() as $file):
            $name = Carbon::createFromFormat('d-m-Y', Carbon::now()) . '-' . Str::random(30);
            $file->storeAs("protected/{$operation}/{$index}/", "{$name}.{$file->getClientOriginalExtension()}");
            tap(PhotosAccess::create([
                'user_id' => $access->data->user_id,
                'operation' => $operation,
                'index' => $index,
                'path' => "{$name}.{$file->getClientOriginalExtension()}",
            ]), function(PhotosAccess $photo) {
                $files[] = $photo->id;
            });
        endforeach;

        /**
         * TODO: Create endpoint on mydomain as confirmation
         */

        return redirect()->away('https://mydomain.co.uk/dashboard');
    }
    catch (Exception $e)
    {
        abort(404);
    }

});

【问题讨论】:

    标签: php html laravel guzzle


    【解决方案1】:

    您可以使用attach() 附加多个文件。附加是一个递归函数。检查here

    $response = Http::withToken(/*your whole JWT process*/); // will add a jwt token
    
    foreach($request->allFiles() as $key => $files)
        foreach($files as $file)
            $response->attach('photos['. Str::random(20).']', file_get_contents($file->getRealPath()), Str::random(20) . '.jpg');
    
    $response = $response->post($url);
    

    【讨论】:

    • 谢谢!!这有助于加载!
    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 2019-06-17
    • 1970-01-01
    • 2020-06-04
    • 2019-12-08
    • 2017-12-25
    • 2021-12-26
    • 2017-11-15
    相关资源
    最近更新 更多