简体   繁体   中英

Call rest API to upload file with form data using cUrl PHP

I have an API to upload file

in Postman it is working fine (see link http://prntscr.com/oirpnb ) so ho can I implement in my PHP code?

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://localhost/test/api/api/retailer/shop/update/image",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => "------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"shopId\"\r\n\r\n50\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW\r\nContent-Disposition: form-data; name=\"image\"; filename=\"apple-brunette-diet-41543.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n\r\n------WebKitFormBoundary7MA4YWxkTrZu0gW--",
  CURLOPT_HTTPHEADER => array(
    "Accept: */*",
    "Authorization: cU5GMlkzWjFkZ3lFemRiMXdTVDk1Mk5JM2tzMHhtckxvMk9mOUdVN1VLbkZFYWZMTGN1b1l0cXJPcVBO5d369cdab2d74",
    "Cache-Control: no-cache",
    "Connection: keep-alive",
    "Host: localhost",
    "Postman-Token: e35c2fc5-6b2a-4047-964e-a97a8ea51e28,0403395b-eae3-4971-94b5-e756657ad932",
    "User-Agent: PostmanRuntime/7.15.0",
    "accept-encoding: gzip, deflate",
    "cache-control: no-cache",
    "content-length: 91755",
    "content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

Now, how can i use this in my PHP code?

$file = $request->file('image');
$filePath = $file->getPathName();
$type = 'image/jpeg';
$fileName = $file->getClientOriginalName();

$data = array(
    'shopId' => 50,
    'image' => curl_file_create($filePath, $type, $fileName)
);

$apiEndPoint='http://localhost/test/api/api/retailer/shop/update/image';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiEndPoint);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM