0

I can send a POST request successfully with POSTMAN and when I turn the request to code I get:

curl --location --request POST 'https://webservice.apiCommerce/import' \
--form 'id=1186' \
--form 'image=@/C:/collection/img/ecomm/01.jpg'

Now, I am trying the same thing with PHP curl and I don't get the expected result.

    $imagePath = "./img/$fileName";
    $post = [
        "id" => $id,
        "image" => '@'.$imagePath
    ];
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    curl_setopt($ch, CURLOPT_URL, $url);

    $response = curl_exec($ch);
    $payload = json_decode($response, true);

The request gets sent, but the image doesn't get uploaded correctly. Is there a reason why there's a mismatch? I can't figure out what's wrong. I tried removing the header and so forth, but it doesn't seem to make any difference at all. I even hard-coded the img path and it doesn't seem to work.

Sayaman
  • 1,145
  • 4
  • 14
  • 35

1 Answers1

0

The first request is succeeding because it is being encoded as multipart/form-data, as uploads should be. As the curl --help menu explains, the --form name=value command specifies multipart MIME data, as opposed to the --data option and its variants. In the second request, however, you are specifying the content type as application/x-www-urlencoding. This encoding is usually preferred, but will not in this case do what you want.

From the MDN web docs:

Non-alphanumeric characters in both keys and values are percent encoded: this is the reason why this type is not suitable to use with binary data (use multipart/form-data instead)