使用Guzzle 6将文件上传到API端点 [英] Upload file using Guzzle 6 to API endpoint

查看:1412
本文介绍了使用Guzzle 6将文件上传到API端点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用Postman将文件上传到API端点.

I am able to upload a file to an API endpoint using Postman.

我试图将其转换为从表单上传文件,使用Laravel上传并使用Guzzle 6发布到端点.

I am trying to translate that into uploading a file from a form, uploading it using Laravel and posting to the endpoint using Guzzle 6.

它在Postman中的外观的屏幕截图(我故意省略了POST URL)

Screenshot of how it looks in Postman (I purposely left out the POST URL)

下面是单击POSTMAN中的生成代码"链接时生成的文本:

Below is the text it generates when you click the "Generate Code" link in POSTMAN:

POST /api/file-submissions HTTP/1.1
Host: strippedhostname.com
Authorization: Basic 340r9iu34ontoeioir
Cache-Control: no-cache
Postman-Token: 6e0c3123-c07c-ce54-8ba1-0a1a402b53f1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW

----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="FileContents"; filename=""
Content-Type: 


----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="FileInfo"

{ "name": "_aaaa.txt", "clientNumber": "102425", "type": "Writeoff" }
----WebKitFormBoundary7MA4YWxkTrZu0gW

下面是用于保存文件和其他信息的控制器功能.文件正确上传,我可以获取文件信息.

Below is controller function for saving the file and other info. The file uploads correctly, I am able to get the file info.

我认为我遇到的问题是使用正确的数据设置multipart和headers数组.

I think the problem I am having is setting the multipart and headers array with the correct data.

public function fileUploadPost(Request $request)
{
    $data_posted = $request->input();
    $endpoint = "/file-submissions";
    $response = array();
    $file = $request->file('filename');
    $name = time() . '_' . $file->getClientOriginalName();
    $path = base_path() .'/public_html/documents/';

    $resource = fopen($file,"r") or die("File upload Problems");

    $file->move($path, $name);

    // { "name": "test_upload.txt", "clientNumber": "102425", "type": "Writeoff" }
    $fileinfo = array(
        'name'          =>  $name,
        'clientNumber'  =>  "102425",
        'type'          =>  'Writeoff',
    );

    $client = new \GuzzleHttp\Client();

    $res = $client->request('POST', $this->base_api . $endpoint, [
        'auth' => [env('API_USERNAME'), env('API_PASSWORD')],
        'multipart' => [
            [
                'name'  =>  $name,
                'FileContents'  => fopen($path . $name, 'r'),
                'contents'      => fopen($path . $name, 'r'),
                'FileInfo'      => json_encode($fileinfo),
                'headers'       =>  [
                    'Content-Type' => 'text/plain',
                    'Content-Disposition'   => 'form-data; name="FileContents"; filename="'. $name .'"',
                ],
                // 'contents' => $resource,
            ]
        ],
    ]);

    if($res->getStatusCode() != 200) exit("Something happened, could not retrieve data");

    $response = json_decode($res->getBody());

    var_dump($response);
    exit();
}

我收到的错误,使用Laravel的调试视图如何显示的屏幕截图:

The error I am receiving, screenshot of how it displays using Laravel's debugging view:

推荐答案

发布数据的方式是错误的,因此接收到的数据格式不正确.

The way you are POSTing data is wrong, hence received data is malformed.

贪吃的文档:

multipart的值是一个关联数组的数组,每个数组 包含以下键值对:

The value of multipart is an array of associative arrays, each containing the following key value pairs:

name :(字符串,必填)表单字段名称

name: (string, required) the form field name

contents :( StreamInterface/资源/字符串,必填)要在 表单元素.

contents:(StreamInterface/resource/string, required) The data to use in the form element.

headers :(数组)与表单元素一起使用的自定义标头的可选关联数组.

headers: (array) Optional associative array of custom headers to use with the form element.

filename:(字符串)可选 字符串作为部分中的文件名发送.

filename: (string) Optional string to send as the filename in the part.

使用以上列表中的键并设置不必要的标头而不将每个字段分成一个数组将导致发出错误的请求.

Using keys out of above list and setting unnecessary headers without separating each field into one array will result in making a bad request.

$res = $client->request('POST', $this->base_api . $endpoint, [
    'auth'      => [ env('API_USERNAME'), env('API_PASSWORD') ],
    'multipart' => [
        [
            'name'     => 'FileContents',
            'contents' => file_get_contents($path . $name),
            'filename' => $name
        ],
        [
            'name'     => 'FileInfo',
            'contents' => json_encode($fileinfo)
        ]
    ],
]);

这篇关于使用Guzzle 6将文件上传到API端点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆