如何使用 node.js 上传 OneDrive API 文件?

How to OneDrive API file uploads with node.js?

一段时间后,我终于弄清楚了如何使用 oAuth2 以及如何使用刷新令牌创建访问令牌。但是我找不到 node.js 上传文件的样本,我唯一找到的就是这个模块 https://www.npmjs.com/package/onedrive-api

但这对我不起作用,因为我收到此错误 { error: { code: 'unauthenticated', message: 'Authentication failed' } }

此外,如果我使用 'xxxxxxx' 手动输入 accessToken:,结果将是相同的。

但是我在上传访问令牌之前创建了,所以我不知道这是否真的是一个无效的信用问题。但有趣的是,如果我从 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.
获取访问令牌 另外我只使用了范围 Files.readWrite.all 我可能需要允许一些其他范围吗?我的代码是

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

能否将示例代码发送给我,以便使用 node.js 将文件上传到 OneDrive API。会很好。谢谢

编辑:我也尝试用这个上传文件

  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)

});

相同的代码:'unauthenticated' 东西:/

这个示例脚本怎么样?本例的流程如下

  1. 使用刷新令牌检索访问令牌。
  2. 使用访问令牌上传文件。

当您使用此示例时,请导入文件名、您的客户端 ID、客户端密码和刷新令牌。详细信息为https://dev.onedrive.com/items/upload_put.htm.

示例脚本:

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);
        });
    });
});

如果我误解了你的问题,我很抱歉。