0

Basically, I have this form data I'm trying to pass using cURL, here it is hardcoded into boundaries and just sending the request.

$postfields = '--Boundary+0xAbCdEfGbOuNdArY'."\r\n";
$postfields .= 'Content-Disposition: form-data; name="device_timestamp"'."\r\n\r\n";
$postfields .= (time() - (100 * rand(1,6)))."\r\n";
$postfields .= '--Boundary+0xAbCdEfGbOuNdArY'."\r\n";
$postfields .= 'Content-Disposition: form-data; name="photo"; filename="photo"'."\r\n";
$postfields .= 'Content-Type: image/jpeg'."\r\n\r\n";
$postfields .= file_get_contents($path)."\r\n";
$postfields .= '--Boundary+0xAbCdEfGbOuNdArY--'."\r\n";

$result = $this->curl_request('api.com/upload/',$postfields,array(
    CURLOPT_HTTPHEADER => array(
         'Content-type: multipart/form-data; boundary=Boundary+0xAbCdEfGbOuNdArY',
         'Content-Length: '.strlen($postfields),
         'Expect:'
    )
));

How could I pass this data into a function like so?

private function multipart_build_query($fields){
    $retval = '';
    foreach($fields as $key => $value){
        $retval .= "--".$this->boundary."\r\nContent-Disposition: form-data; name=\"$key\"\r\n\r\n$value\r\n";
    }
    $retval .= "--".$this->boundary."--";
    return $retval;
}

I'm kind of guessing I'd have to modify my multipart_build_query due to the following line : Content-Type: image/jpeg

I tried doing the following

$data_array = array(
    "device_timestamp" => (time() - (100 * rand(1,6))),
    "photo" => "@".$path,
);
$body = $curl->multipart_build_query($data_array);

yet to no avail

4

1 回答 1

2

我建议你做一个这样的数组:

$time  = (string) (time() - (100 * rand(1,6)));
$photo = file_get_contents($path);

$fields = array(
    array(
        'headers' => array(
            'Content-Disposition' => 'form-data; name="device_timestamp"',
            'Content-Length'      => strlen($time)
        ),
        'body' => $time
    ),
    array(
        'headers' => array(
            'Content-Disposition' => 'form-data; name="photo"; filename="photo"',
            'Content-Type'        => 'image/jpeg',
            'Content-Length'      => strlen($photo)
        ),
        'body' => $photo
    )
);

该方法可以如下所示:

private function multipart_build_query($fields)
{
    $data = '';

    foreach ($fields as $field) {
        // add boundary
        $data .= '--' . $this->boundary . "\r\n";

        // add headers
        foreach ($field['headers'] as $header => $value) {
            $data .= $header . ': ' . $value . "\r\n";
        }

        // add blank line
        $data .= "\r\n";

        // add body
        $data .= $field['body'] . "\r\n";
    }

    // add closing boundary if there where fields
    if ($data) {
        $data .= $data .= '--' . $this->boundary . "--\r\n";
    }

    return $data;
}

您现在有一个非常通用的方法,它支持任何类型的字段。

于 2013-11-20T13:36:51.663 回答