lbrahim
lbrahim

Reputation: 3810

How to upload any file using MS Graph API?

I am following this and I want to upload any type of file to OneDrive. It says that it accepts a buffer for the file content but my following code does not seem to work in case of any type of file. The file gets uploaded but it cannot be opened so the contents are messed up for sure.

Using the following method I am trying to get the body contents so that I can send them with the request.

private fileToBuffer(file: File): Observable<any> {
    return Observable.create(observer => {
        var arrayBuffer;
        var fileReader = new FileReader();
        fileReader.onload = function () {
            arrayBuffer = this.result;
            observer.next(arrayBuffer);
            observer.complete();
        };
        fileReader.readAsArrayBuffer(file);
    });
}

Upvotes: 0

Views: 1459

Answers (1)

lbrahim
lbrahim

Reputation: 3810

I did not notice that the Angular 2's http's PUT was taking the body as string. So, I resorted to using XHR to upload a file with its contents.

var oReq = new XMLHttpRequest();
oReq.open("PUT", url, true);
oReq.setRequestHeader("Content-Type", "text/plain");
oReq.onload = function(e){
    console.log('done');
};
oReq.send(arrayBuffer);

Upvotes: 2

Related Questions