简体   繁体   中英

Create Word file using Microsoft Graph api

I am trying to create word file using Microsoft Graph API. link

Here is the code for the same.

function createWordFile(token) {
    $.ajax({
        url: 'https://graph.microsoft.com/v1.0/me/drive/root:/FolderA/FileU.docx:/content',
        method: 'PUT',
        headers: {
            'authorization': 'Bearer ' + token,
            "content-type": "text/plain",
            'Accept': 'application/json;odata.metadata=full'
        },
        data: 'test',
        transformRequest: []
    }).success(function (result) {
        console.log(result);
    }).error(function (err) {
        console.log(err);
    });
}

File is created successfully.But it is corrupted, not opening either in Word Online or Word Desktop App.

It gives following error.

在此处输入图片说明

the Microsoft Graph API does not have a method to create a file so we use the file upload method, but this case must be a binary. just remove the data attribute and it will work perfect.

 function createWordFile(token) { $.ajax({ url: 'https://graph.microsoft.com/v1.0/me/drive/root:/FolderA/FileU.docx:/content', method: 'PUT', headers: { 'authorization': 'Bearer ' + token, "content-type": "text/plain", 'Accept': 'application/json;odata.metadata=full' }, data: 'test', transformRequest: [] }).success(function (result) { console.log(result); }).error(function (err) { console.log(err); }); } token = `eyJ0eXAiOiJKV1QiLCJub25jZSI6ImFTek05SzJiU1JyWllubjhaUlYyOFpESGp6bmxtQno1Y1VmVjNHMVYxeXMiLCJhbGciOiJSUzI1NiIsIng1dCI6IkN0VHVoTUptRDVNN0RMZHpEMnYyeDNRS1NSWSIsImtpZCI6IkN0VHVoTUptRDVNN0RMZHpEMnYyeDNRS1NSWSJ9..bErjeWOc2xOqi4PiGmRZnxrlvjHXfBTMxKRS0wD9IjyKqx8SJiHGkewsrVXjUekdO74hfixgDY4Ykf2E_dGPKdHPBtu0SScu_KT4zSSfZubs4IYu8bZL0k8c19Sv6DffC9IPayGv7un4cmObG6sUw5_N28hXtvg-HImcrwkep5gt5xmRP2yqpdL_XZ2DjTGBh_rc6ZnFIUMptl7_6s07arD9Rlheyn7faERR_94bSl4hiEGTrUlPCDuTxpo9BfWMqyAeOec4aoviCJvZD5ySfTCIRbTuyXRPndwBwNIuQX3lQRpMB1I60pGO-7gYX04vslpFwIXWQ1x2CyPsKjeLjw` createWordFile(token)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

The trick is found is to host a .xlsx or .pptx blank file in my project. And when I need to create a new file in OneDrive from javascript, I fetch the document like below :

return (fetch('/assets/file-samples/template.xlsx')
            .then((res) => {
                return res.arrayBuffer();
            })
            .then((buf) => {
                return new File([buf], 'template.xlsx', {type: 
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
            })
    );

One I have my file. I am now able to create a document using Microsoft Graph Client Javascript SDK like below :

this.getSampleFile(fileType, extension).then((blankFile) => {
                    client.api('me/drive/root:/yourfolder/' + 'yourName.xlsx' + ':/content')
                        .put(blankFile).then((file) => {
                        console.log(file)
                    }, (err) => {
                        console.log(err)
                    });
                });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM