Curl file upload with multipart/form-data Curl file upload with multipart/form-data curl curl

Curl file upload with multipart/form-data


Replace this line:

$postdata = array("file[]" => "@/".realpath($file));

with:

$postdata = array("file[]" => "@/".realpath($file).";type=video/mp4");

and it should work.


I've used curl for connecting with a web service and upload a file using a similar idea of this post, but it didn't work. The reasons where different to the previous answer, so I will describe my solution; maybe my experience is useful to others.

I had two problems. The first one is that my web service didn't like absolute path in the filename. If $file in the OP code has a path, then using:

$postdata = array('file[]' => "@/".realpath($file));

becomes:

Content-Disposition: form-data; name="file[]"; filename="/tmp/iy56ham"

and that path generated a BAD REQUEST. So I had to use chdir, basename and dirname in order to avoid using paths in the $postdata.

On the other hand, curl sent an extra header, not shown in the OP:

Expect: 100-continue

My web service didn't like it (neither twitter WS) and it answered with a:

417 Expectation Failed

To avoid curl sending that offending header you can use:

curl_setopt( $curlHandler, CURLOPT_HTTPHEADER, array('Expect:') );

so you set an empty Expect header and curl will not overwritten with 100-continue.

Hope this help someone...