如何在cakephp3中使用文件发布多部分请求?

问题描述 投票:0回答:1

我在使用 http 客户端在 cakephp 3 中发布文件数据时遇到麻烦。下面是我正在使用的代码。

用于在控制器顶部形成数据

use Cake\Http\Client\FormData;

在提交表单之前创建

fromData
的对象

$data = new FormData();

将整个表单数据收集到数组中

$parametersArray = array(
    'parentTypeId'          => $userDetail->userTypeId,
    'parentId'              => $userDetail->userTypeId,
    'canChangeTrainingPlan' => false,
    'userObject' => array(
        'userTypeId'        => $this->request->data['user_type'],
        'userProfile' => array(
            'firstName'     => $this->request->data['first_name'],
            'lastName'      => $this->request->data['last_name'],
            'dateOfBirth'   => $this->request->data['user_dob'],
            'email'         => $this->request->data['user_email'],
            'phone'         => $this->request->data['user_phone'],
            'profileImage'  => $this->request->data['imageFile']['name'],
            'houseNumber'   => $this->request->data['house_number'],
            'streetNumber'  => $this->request->data['street_number'],
            'locality'      => $this->request->data['user_localty'],
            'landmark'      => $this->request->data['user_landmark'],
            'city'          => $this->request->data['user_city'],
            'state'         => $this->request->data['user_state'],
            'country'       => $this->request->data['user_country'],
            'pincode'       => $this->request->data['user_type'],
        )
    )
);

在第三方 API 中为帖子创建最终数组

$finalArray = array(
    'imageFile'  => $this->request->data['imageFile']['name'],
    'postData'   => json_encode($parametersArray),
);

将数据数组添加到formData

$data->add($parametersArray);

现在使用文档中提到的添加文件代码 https://book.cakephp.org/3.0/en/core-libraries/httpclient.html

// This will append the file to the form data as well.
$file = $data->addFile('imageFile', $this->request->data['imageFile']);
$file->contentId($this->request->data['imageFile']['name']);
$file->disposition('attachment');

// Send the request.
$response = $http->post(
    BASE_API_URL.'user/register/'.$userDetail->id,
    $data,
    ['headers' => ['Content-Type' => $data->contentType()]]
);

现在的问题是我很少收到

file_get_contents()
的警告和来自 API 的 Response 400 Bad Request。
API 工作正常,使用 postman 进行了测试。

API 需要输入、输出和响应

URL:    {BASE_URL}/user/register/{currentUserId}    
Input:  {currentUserId} the logged in user id
    Form Data with following params:    
    imageFile   the user profile image file selected from PC
    postData    "{
""parentTypeId"":1,
""parentId"":1,
""canChangeTrainingPlan"":false,
""userObject"":{""id"":5,""userTypeId"":3,""userProfile"":{""firstName"":""Jyotsana"",""lastName"":""Arora"",""dateOfBirth"":""1989-07-16"",""email"":""[email protected]"",""phone"":"""",""profileImage"":""<FILE_NAME>"",""houseNumber"":"""",""streetNumber"":"""",""locality"":"""",""landmark"":"""",""city"":"""",""state"":"""",""country"":"""",""pincode"":""160022""}}}
""profileImage"" key must contain the selected File name"
API Params  API must have following parameters: 
    enctype:    multipart/form-data'
    contentType:    false
    processData:    false
    cache:  false
Output:     "User object with complete details:
USER_ID > 0 : Successful Registration
USER_ID = 0 : Current user is not allowed to register this user
USER_ID = -1: Server Error
USER_ID = -2: Current User Id is invalid
USER_ID = -3: Input User object is not correct
USER_ID = -4: Email already exists
USER_ID = -8: Parent Id is invalid"
cakephp cakephp-3.0
1个回答
2
投票

你误读了文档,你不能传递文件上传数组,既不能传递给

HttpClient::post()
,也不能传递给
FormData::addFile()
。这些示例显示了如何从请求传递用户数据,只是演示了如何明智地执行此操作,因为前面带有
@
的字符串将被解释为本地/远程文件包含路径(这就是帽子部分中提到的原因) .

长话短说,

FormData::addFile()
仅接受文件资源句柄,或以
@
开头的文件包含路径(但如红色警告框中所述,已弃用)。因此,如文档中的第一个示例所示,传递文件句柄应该可以解决生成无效表单数据的问题。

$file = $data->addFile(
    'imageFile',
    fopen($this->request->data['imageFile']['tmp_name'], 'r')
);

您还应该将数据显式转换为字符串,如示例所示:

$response = $http->post(
    BASE_API_URL.'user/register/'.$userDetail->id,
    (string)$data, // <<< cast data to a string
    ['headers' => ['Content-Type' => $data->contentType()]]
);

另请参阅

© www.soinside.com 2019 - 2024. All rights reserved.