【问题标题】:How to upload file using Laravel Guzzle HTTP client如何使用 Laravel Guzzle HTTP 客户端上传文件
【发布时间】:2021-01-06 22:03:39
【问题描述】:

我正在使用 Laravel 应用程序中的 Alfresco Rest API!

为此,我使用 laravel guzzlehttp/guzzle 包。

下面是我的代码。

当我运行它时,我得到一个状态 400

我的端点的文档可以在这里找到:https://api-explorer.alfresco.com/api-explorer/#!/nodes/createNode


// AlfrescoService.php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\Response;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;

class AlfrescoService
{
    public static function apiConnexion()
    {
        $response = Http::withHeaders([
            "Content-Type" => "application/json",
        ])->post('http://192.168.43.152:8080/alfresco/api/-default-/public/authentication/versions/1/tickets', [
            'userId' => 'admin',
            'password' => 'admin',
        ]);
    return  base64_encode( $response["entry"]["id"] );

    }

    public static function request2($queryType, String $query, array $data=[])
    {

        $response = Http::withHeaders([
            "Authorization" => "Basic ".self::apiConnexion(),
        ])->attach(
            'attachment', file_get_contents('alfresco/doc.txt'), 'doc.txt'
        )->$queryType('http://192.168.43.152:8080/alfresco/api/-default-/public/alfresco/versions/1'.$query, $data);

        return $response;
    }


}



// AlfrescoController.php


namespace App\Http\Controllers;


use App\Http\Controllers\Controller;
use App\Services\AlfrescoService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use MercurySeries\Flashy\Flashy;

class AlfrescoController extends Controller
{

    public function storeFile(Request $request) {

        $data=["name"=>"My new File.txt", "nodeType"=>"cm:content"];
        $response=AlfrescoService::request2("post", "/nodes/-shared-/children", $data);

        dd($response->status()); // 400

    }

}

【问题讨论】:

  • 如果您通过 API 调用告诉我们您想做什么,将会很有帮助。
  • 你为什么使用 $queryType

标签: laravel alfresco guzzle


【解决方案1】:

回复应提及导致错误请求的原因。您可以尝试wireshark 捕获上传尝试并将其与 curl 示例进行比较here

【讨论】:

    【解决方案2】:

    我不明白您为什么使用 $querytype,但正如您在标题“如何使用 Laravel Guzzle HTTP 客户端上传文件”中所问的那样,所以这是答案,

    public static function request2($queryType, String $query, array $data=[])
        {
            
            $file = fopen('alfresco/doc.txt', 'r')
    
            $response = Http::withToken(self::apiConnexion())
                ->attach('attachment', $file)
                ->post($url);
    
            return $response;
        }
    

    可以在docs看到withToken()方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 2021-10-27
      • 2020-11-20
      相关资源
      最近更新 更多