PHP Converting an Image to add Multipart Form Data

浪子不回头ぞ 提交于 2019-12-11 07:39:08

问题


I am having some difficulty with an API. It has requested that I create a Multipart Form Data image

POST https://api.working.com/v1/detail/detail.example.id1/27f145d2-5713-4a8d-af64-b269f95ade3b/images/thumbnail/normal

------------------------------330184f75e21
Content-Disposition: form-data; name="image"; filename="icon.png"
Content-Type: application/octet-stream

.PNG
imagedata
Response

I am trying to find some example PHP script that will convert an image into this format

The image file must have the name image in the multipart form data

I am racking my brain and combing the internet to find something that works for me.

Does anyone have a snippet they can share please to help?

Thanks

Rob


回答1:


Here's a basic curl example showing how to do it:

$url = 'https://api.working.com/v1/detail/detail.example.id1/27f145d2-5713-4a8d-af64-b269f95ade3b/images/thumbnail/normal';

$data = array(
    'image' => new CURLFile(
        '/path/to/icon.png', 
        'application/octet-string',
        'icon.png'
     ),
    'some_other_field' => 'abc',
);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HEADER, 0);

$response = curl_exec($ch);

// do something with response

// to debug, try var_dump(curl_getinfo($ch)); and var_dump(curl_error($ch));

$ch = curl_init($url);

Check out the CURLFile class for more info on file uploads, and curl_setopt() for more request options.



来源:https://stackoverflow.com/questions/37451966/php-converting-an-image-to-add-multipart-form-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!