Search code examples
phplaravelguzzlegitlab-api

How to Commit Mp3 Files to Folders in Gitlab through API


I am trying to commit a file to Gitlab through the API.

The code had been working for over 6 months but now has stopped working, nothing in the code had changed. The file is commited to Gitlab, however it is corrupted.

I have went through the Guzzle documentation and everything looks correct, and I have done the same for the Gitlab documentation about commits.

I am now using the Laravel Illuminate/Http class to send the commits but the same thing is still happening. I am able to commit to Gitlab, but the file is not formatted correctly.

$response = Http::withHeaders([
    'PRIVATE-TOKEN' => $gitlab_token,
])
    ->post('https://gitlab.com/api/v4/projects/.../repository/commits/', [
        'branch' => 'test-branch',
        'commit_message' => 'Updated audio file test.mp3',
        'actions' => array(array(
            'action' => 'update',
            'file_path' => 'filePath/../.mp3',
            'content' => base64_encode($var)
        )),
    ]);

If I do not encode the contents of the file to base 64 I get the error:

Malformed UTF-8 characters, possibly incorrectly encoded in file

Has anything changed on the API side that has effected how files are processed for committing? Has anyone else found a solution?


Solution

  • I think you have two problems; first there's no content type specified. The post request will be sent just as multipart/form-data with a file attachment, or application/x-www-url-encoded without. This API is expecting JSON data.

    Second, there is a parameter in the commit endpoint to specify file encoding. It defaults to "text" but you are sending a base64-encoded file.

    I'm not familiar enough with the Gitlab API to say for sure, but your file_path property looks strange as well; shouldn't it just be ".mp3" to be put into that directory?

    Try this:

    $response = Http::withHeaders([
        'PRIVATE-TOKEN' => $gitlab_token,
        'Content-Type' => 'application/json',
    ])
        ->post('https://gitlab.com/api/v4/projects/.../repository/commits/', [
            'branch' => 'test-branch',
            'commit_message' => 'Updated audio file test.mp3',
            'actions' => [
                [
                    'action' => 'update',
                    'file_path' => '.mp3',
                    'content' => base64_encode($var),
                    'encoding' => 'base64',
                ]
            ],
        ]);