Box api v2 upload file using php

424 views Asked by At

I have been working on box api. I could get everything to work but the file upload. Here is the code:

$path = 'https://upload.box.com/api/2.0/files/content';
$method = 'POST';
$headers = array('Authorization Bearer ' . $accessToken);
$attributes = array('name'=>$file_name, 'parent'=>array('id'=>0));
$body = array('attributes'=>json_encode($attributes), 'file'=>'@'.realpath($filepath));
$result = $this->post($path, $method, $body, $headers);

and pass all of that to a post function:

function post($url,$method, $fields, $headers){
    try {
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $response = curl_exec($ch);
        $responseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if (false === $response) {
            $errNo = curl_errno($ch);
            $errStr = curl_error($ch);
        }
        curl_close($ch);

    } catch (Exception $e) {
        $response = $e->getMessage();
    }

    return $responseCode;
}

I get 400 error using this but if I add this line $body = http_build_query($body, '', '&'); before calling the post function I'll get a 405 error.

In both cases though the upload is not working. I made sure to pass the actual path of the file not the relative path in case anyone is wondering.

I also checked solutions like this: https://github.com/golchha21/BoxPHPAPI but that didn't work either.

Any idea on the issue and how to fix it?

1

There are 1 answers

0
Kelsey On

Have you attempted making this same request in the Chrome plugin POSTman? I am not sure about your post function but here is the command in curl

curl https://upload.box.com/api/2.0/files/content -H "Authorization: Bearer ACCESS_TOKEN" -X POST -F attributes='{"name":"myFile.jpeg", "parent":{"id":"0"}}' -F file=@FILE_PATH