Search code examples
onedrive

How to upload a new file to OneDrive using new API?


I'm trying to get file uploads working with the new OneDrive API. I'm starting out with just simple files (i.e. < 100MB) with the intention of progressing to resumable uploads once I've got the simple ones working!

I've tried using http://onedrive.github.io/items/upload_put.htm but I'm getting 403 back. I thought that this might be because the file didn't already exist but I've uploaded the file using the OneDrive web UI successfully and the code still can't upload the file.

The URL I'm using is something like:

https://api.onedrive.com/v1.0/drive/root:/:/content?access_token=

The C# code is:

        using (Stream fileStream = await file.OpenStreamForReadAsync())
        {
            try
            {
                HttpStreamContent streamContent = new HttpStreamContent(fileStream.AsInputStream());

                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Put, oneDriveURI);
                request.Content = streamContent;
                request.Content.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/octet-stream");

                HttpResponseMessage response = await client.SendRequestAsync(request);
                Debug.WriteLine("UploadFileToOneDrive: response = {0}", response.StatusCode);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("UploadFileToOneDrive failed with exception {0}", ex.Message);
            }
        }

What have I got wrong/misunderstood? The API documentation needs a LOT more examples :-(


Solution

  • 403 error code is related to permissions so it could be possible that you may have forgotten to include the proper scopes to upload the file. When you send your OAuth request, you'll want to also include "onedrive.readwrite" as one of the scopes.

    GET https://login.live.com/oauth20_authorize.srf?client_id={client_id}&scope={scope}&response_type=token&redirect_uri={redirect_uri}

    More scopes can be found at "http://onedrive.github.io/auth/msa_oauth.htm". I hope that helps.