Search code examples
phpcurlonedrive

cURL POST file to OneDrive


I'm trying to upload a file to a users folder on OneDrive using their API.

    $cfile = curl_file_create(realpath($_POST['ppt-file']));

    //place file in folder
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://apis.live.net/v5.0/". $my_folder ."/files?access_token=" . $access_token);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $cfile);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $upload_result = trim(curl_exec($ch));
    curl_close($ch);

I get a response from the API.

The request entity body has an incorrect value in the 'Content-Disposition' header. The expected format for this value is 'Content-Disposition: form-data; name="file"; filename="[FileName]"'."

Not sure where I'm going wrong, but this is the http header that's expected.

POST https://apis.live.net/v5.0/me/skydrive/files?access_token=ACCESS_TOKEN

Content-Type: multipart/form-data; boundary=A300x

--A300x
Content-Disposition: form-data; name="file"; filename="HelloWorld.txt"
Content-Type: application/octet-stream

Hello, World!
--A300x--

Thanks in advance!

Update: When I put the API url directly in my action attribute of my form and rename my file input field to 'file', the file gets uploaded. But then I just get the response printed on my page :) not want I want to happen ofcourse.

 <form action="<?php echo "https://apis.live.net/v5.0/". $my_folder ."/files?access_token=" . $access_token; ?>" method="post" enctype='multipart/form-data'>
    <input type="file" name="file"/>
    <input type="submit" value="Upload your ppt" name="btnUpload"/>
 </form>

Solution

  • Apparently the only way to do POST a file to the OneDrive API is by doing it directly in your form like this. And providing a redirect_uri. The response will come in the form of a pound value attached to your URL. Which is not ideal, since I'll have to get my file id with javascript.

    <form action="<?php echo "https://apis.live.net/v5.0/". $your_folder ."/files?access_token=" . $access_token . "&redirect_uri=http%3A%2F%2Fwww.whateverredirect.com"; ?>" method="post" enctype="multipart/form-data">
        <input type="file" name="file"/>
        <input type="submit" value="Upload your ppt" name="btnUpload"/>
    </form>
    

    I'd still like to do this in a curl type fashion, giving me a proper json response. So if anyone knows how, please do let me know!