How to OneDrive API file uploads with node.js?

2019-07-30 12:42发布

问题:

After a time I finally figure out how to use oAuth2 and how to create a access token with the refresh token. But I can´t find node.js samples for upload files the only thing I found was this module https://www.npmjs.com/package/onedrive-api

But this didn´t work for me because I get this error { error: { code: 'unauthenticated', message: 'Authentication failed' } }

Also if I would enter accessToken: manually with 'xxxxxxx' the result would be the same.

But I created before the upload the access token so I don´t know if this really can be a invalid credits problem. But the funny thing is if I would take the access token from https://dev.onedrive.com/auth/msa_oauth.htm where you can generate a 1h access token the upload function works. I created my auth with the awnser from this question. OneDrive Code Flow Public clients can't send a client secret - Node.js
Also I only used the scope Files.readWrite.all do I maybe need to allow some other scopes ? My code is

const oneDriveAPI = require('onedrive-api');
const onedrive_json_configFile = fs.readFileSync('./config/onedrive.json', 'utf8');
const onedrive_json_config = JSON.parse(onedrive_json_configFile);
const onedrive_refresh_token = onedrive_json_config.refresh_token
const onedrive_client_secret = onedrive_json_config.client_secret
const onedrive_client_id = onedrive_json_config.client_id






// use the refresh token to create access token
request.post({
    url:'https://login.microsoftonline.com/common/oauth2/v2.0/token',
    form: {
        redirect_uri: 'http://localhost/dashboard',
        client_id: onedrive_client_id,
        client_secret: onedrive_client_secret,
        refresh_token: onedrive_refresh_token,
        grant_type: 'refresh_token'
    }
}, function(err,httpResponse,body){
if (err) {
console.log('err: ' + err)
}else{
console.log('body full: ' + body)
var temp = body.toString()
temp = temp.match(/["]access[_]token["][:]["](.*?)["]/gmi)
//console.log('temp1: ', temp)
temp = temp.join("")
temp = temp.replace('"access_token":"','')
temp = temp.replace('"','')
temp = temp.replace('\n','')
temp = temp.replace('\r','')
//console.log('temp4: ', temp)



oneDriveAPI.items.uploadSimple({
  accessToken: temp,
  filename: 'box.zip',
  parentPath: 'test',
  readableStream: fs.createReadStream('C:\\Exports\\box.zip')
})
.then((item,body) => {
console.log('item file upload OneDrive: ', item); 
console.log('body file upload OneDrive: ', body); 
// returns body of https://dev.onedrive.com/items/upload_put.htm#response 
})
.catch((err) => {
console.log('Error while uploading File to OneDrive: ', err); 
});



} // else from if (err) { from request.post
}); // request.post({ get access token with refresh token

Can you send me your sample codes please to upload a file to OneDrive API with node.js. Would be great. Thank you

Edit: I also tried to upload a file with this

  var uri = 'https://api.onedrive.com/v1.0/drive/root:/' + 'C:/files/file.zip' + ':/content'

  var options = {
      method: 'PUT',
      uri: uri,
      headers: {
        Authorization: "Bearer " + accesstoken
      },
      json: true
    };

request(options, function (err, res, body){

if (err) {
console.log('#4224 err:', err)
}
console.log('#4224 body:', body)

});

Same code: 'unauthenticated' stuff :/

回答1:

How about this sample script? The flow of this sample is as follows.

  1. Retrieve access token using refresh token.
  2. Upload a file using access token.

When you use this sample, please import filename, your client id, client secret and refresh token. The detail information is https://dev.onedrive.com/items/upload_put.htm.

Sample script :

var fs = require('fs');
var mime = require('mime');
var request = require('request');

var file = 'c:/Exports/box.zip'; // Filename you want to upload on your local PC
var onedrive_folder = 'samplefolder'; // Folder name on OneDrive
var onedrive_filename = 'box.zip'; // Filename on OneDrive

request.post({
    url: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
    form: {
        redirect_uri: 'http://localhost/dashboard',
        client_id: onedrive_client_id,
        client_secret: onedrive_client_secret,
        refresh_token: onedrive_refresh_token,
        grant_type: 'refresh_token'
    },
}, function(error, response, body) {
    fs.readFile(file, function read(e, f) {
        request.put({
            url: 'https://graph.microsoft.com/v1.0/drive/root:/' + onedrive_folder + '/' + onedrive_filename + ':/content',
            headers: {
                'Authorization': "Bearer " + JSON.parse(body).access_token,
                'Content-Type': mime.lookup(file),
            },
            body: f,
        }, function(er, re, bo) {
            console.log(bo);
        });
    });
});

If I misunderstand your question, I'm sorry.