0

I want to upload a file to a sub folder of a document Library in Sharepoint Online.

I have an error when posting the file: "URL is not web relative". I don't understand because I can read the content of the sub folder with a GET Request.

My file full path exists, I can read it and transform it to a ByteArrayContent.

My code:

 // Upload
                using (HttpClient client = new HttpClient())
                {
                    // Access Token with Bearer
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"Bearer { accessToken }");

                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/json;odata=verbose");

                    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json;odata=verbose");

                    try
                    {
                        // Ok, I can get the result from this url
                        string uriGet = $"{ _baseUri }/_api/web/getFolderByServerRelativeUrl('Shared Documents/MyFolder')";

                        var resultGet = await client.GetAsync(uriGet);
                        var stringResultGet = await resultGet.Content.ReadAsStringAsync();

                        // But, posting a file isn't working on the same folder
                        string uri = $"{ _baseUri }/_api/web/getFolderByServerRelativeUrl('Shared Documents/MyFolder')/files/add(url='{ fileFullPath }', overwrite=true)";

                        var bytes = System.IO.File.ReadAllBytes(fileFullPath);

                        ByteArrayContent byteArrayContent = new ByteArrayContent(bytes);

                        var result = await client.PostAsync(uri, byteArrayContent);

                        var stringResult = await result.Content.ReadAsStringAsync();
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }

                }

Thanks for your help !

2
  • I don't have the rep here to comment... sorry Can you explain how you can specify a path when you can only specify a file name? Is that only possible by changing the current directory?
    – Siete
    Nov 1, 2022 at 15:19
  • You can ask a new question using Ask Question. Provide link to this post as it provides context for your question. Nov 1, 2022 at 15:23

1 Answer 1

1

You shouldn't specify the complete URL of the file in here: .../files/add(url='{ fileFullPath }', overwrite=true)";

Just specify the filename within the folder. ex.: document.docx.

1
  • Thank you very much, it solved my issue
    – GwenGuts
    Aug 24, 2020 at 7:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.