I can't make a request to the glpi API to upload a file

Viewed 28

I'm trying to create an application with files in glpi via the C# API.

Creating an application works, but I can't do file uploads. Based on the file upload documentation, I have to send a POST request to http://path/to/glpi/api/Document/1 with files in multipart/form-data format.

How do I send such a curl request in C#?

$ curl -X POST \
-H 'Content-Type: multipart/form-data' \
-H "Session-Token: 83af7e620c83a50a18d3eac2f6ed05a3ca0bea62" \
-H "App-Token: f7g3csp8mgatg5ebc5elnazakw20i9fyev1qopya7" \
-F 'uploadManifest={"input": {"name": "Uploaded document", "_filename" : 
   ["file.txt"]}};type=application/json' \
-F 'filename[0]=@file.txt' \
'http://path/to/glpi/apirest.php/Document/'

Here's what I have at the moment:

    private async Task UploadFiles(GlpiTicket ticket)
    {
        var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Add("Authorization", $"user_token {_apiClientToken}");
        httpClient.DefaultRequestHeaders.Add("Session-Token", SessionToken);
        httpClient.DefaultRequestHeaders.Add("App-Token", _appToken);
        var form = new MultipartFormDataContent();
        form.Headers.ContentType.MediaType = "multipart/form-data";
        ticket.FileNames.ForEach(pathToFile =>
        {
            try
            {
                var fileStream = File.OpenRead(pathToFile);
                form.Add(new StreamContent(fileStream), Guid.NewGuid().ToString(), pathToFile);
            } catch (Exception) {
                // ignored
            }
        });
        var response = await httpClient.PostAsync($"{RestUrl}/Document/", form);
        httpClient.Dispose();
        var sd = response.Content.ReadAsStringAsync().Result;
        MessageBox.Show(sd);
    }
0 Answers
Related