Upload CSV file to google drive with curl fails: "Bad content type. Please use multipart."

I’m trying to upload a CSV file to google drive and I’m getting the error described in the subject of this post. I’m using CURL and Yii 1.1

this is my code:

I think my error is in the content generation. I’ve seen some other posts but I can’t resolve it yet.

this is the code:

public function uploadFileToDrive($token, $fileContent){
        echo "Iniciando subida de archivo a drive .... \n";
        
        try {
            $apiUrl = 'https://www.googleapis.com/';
            $ch1 = curl_init();

           
            /* MEtODO 1 */
            $mime_type = 'text/csv';
            $data = '
            --section_divider
            Content-Type: application/json; charset=UTF-8
            {
                "name": "test.xlsx",
            }

            --section_divider
            Content-Type: '.$mime_type.',
            '.$fileContent.'
            --section_divider--
            ';

           
            //print_r($body);die();
            curl_setopt($ch1, CURLOPT_URL, $apiUrl . 'upload/drive/v3/files?uploadType=multipart');
            curl_setopt($ch1, CURLOPT_POST, 1);
            curl_setopt($ch1, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);

            curl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: multipart/related;section_divider', 'Authorization: Bearer' . $token) );

            $response = curl_exec($ch1);
            if ($response === false) {
                echo 'Curl error: ' . curl_error($ch1);
            } else {
                echo "Operation completed without any errors \n";
                $output = $response;
            }
            curl_close($ch1);
            var_dump($output);die();
            return $output;

        } catch (Exception $e) {
            print "An error occurred: " . $e->getMessage();
        }

    }

I don’t know what I’m doing wrong

I hope you can give some advice
thanks

The expected results. See the CSV file uploaded on google drive.

See in the console a response indicating that all it’s done

I guess you have solved your problem by now, but if anyone have this problem, you need to add a header to your query. Take a look at this solution:

1 Like