【问题标题】:How to OneDrive API file uploads with node.js?如何使用 node.js 上传 OneDrive API 文件?
【发布时间】:2018-01-09 03:31:25
【问题描述】:

一段时间后,我终于弄清楚如何使用 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 获取访问令牌,您可以在其中生成一个 1h 访问令牌,上传功能就可以工作。我用这个问题的 awnser 创建了我的身份验证。 OneDrive Code Flow Public clients can't send a client secret - Node.js
另外我只使用了范围 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)

});

相同的代码:“未经身份验证”的东西:/

【问题讨论】:

    标签: node.js oauth-2.0 onedrive


    【解决方案1】:

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

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

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

    【讨论】:

    • 你又拯救了我的一天。非常感谢
    • 嘿,遗憾的是,您的代码仅适用于 4MB 以下的文件。你有上传会话的工作示例代码吗?我在这里遇到了与此相关的新问题stackoverflow.com/questions/45684079/…
    • @t33n 欢迎。也谢谢你。我试着考虑上传大尺寸文件。
    • @Tanaike:对不起这个愚蠢的问题:我怎样才能得到refresh_token?我在 Azure 应用程序中找不到这个。在 Azure 应用中,我可以看到 client_id 和 client_secret。
    • @Saurabh Chauhan 感谢您的评论。这个问题不是你的问题。因此,我们无法在此问题中发布您的问题的答案。那么,您能否通过包含更多信息将您的问题作为新问题发布?这样,它将帮助包括我在内的用户思考解决方案并发布答案。而且,我认为这样的答案对有同样问题的其他用户很有用。如果您能合作解决您的问题,我很高兴。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多