How to make REST call to MS Graph/OneDrive method with OAuth2

老子叫甜甜 提交于 2019-12-25 08:37:55

问题


I am trying to use the OneDrive API and I have successfully registered my app through their Application Registration Portal. I can call successfully call the Javascript FilePicker SDK to upload and download files

That demonstrates that I have my app registered properly and the proper app/client-id's.

Now I'd like to use the REST services to upload and download files but I'm not sure how to send authentication and I don't know how to make the call to the proper URL.

My first question is: How can I use the token I created in the reg service to make a REST call?

My second question is: What syntax should I use to upload a file? I don't know where to put the URL to make the call.

The PUT documentation for their upload is found here

    <script type="text/javascript">
        function launchSaveToOneDrive(){
            var xhttp = new XMLHttpRequest();
            //Authorization: bearer {token} 
            xhttp.open("PUT", "/drive/items/{parent-id}:/{filename}:/content", false);
            xmlhttp.setRequestHeader("Authorization", "Bearer-xxxxxxxxxxxxxxxxxxx");
            xhttp.setRequestHeader("Content-type", "text/plain"); 
            xhttp.send();
            var response = JSON.parse(xhttp.responseText);
        }
        </script>

回答1:


One option is to use the Microsoft Graph JavaScript SDK that can help with REST calls including uploading files to OneDrive through the MS Graph. The library works with client side JavaScript and Node for JavaScript server apps.

Check the Browser folder under samples to see how to use the SDK in a client app. Uploading a file would look something like this (see that link for the full code):

    // file variable is from the contents of an input field for example 
    var file = document.querySelector('input[type=file]').files[0];

    // after user selects a file from the file picker

   client
       .api('/me/drive/root/children/Book.xlsx/content')
       .put(file, (error, response) => {
           // supports callbacks and promises
        });


来源:https://stackoverflow.com/questions/44640533/how-to-make-rest-call-to-ms-graph-onedrive-method-with-oauth2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!