如何使用node.js上传OneDrive API文件? [英] How to OneDrive API file uploads with node.js?

查看:262
本文介绍了如何使用node.js上传OneDrive API文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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' } }

此外,如果我输入accessToken:用'xxxxxxx'手动输入,结果将相同.

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

但是我是在上传访问令牌之前创建的,所以我不知道这是否真的可能是无效的积分问题.但是有趣的是,如果我要从 https://dev.onedrive.com获取访问令牌/auth/msa_oauth.htm ,您可以在其中生成1小时访问令牌,上传功能可以正常工作.我用这个问题的遮篷创建了auth. OneDrive代码流公共客户端无法发送客户端机密-Node.js
我也只使用了范围Files.readWrite.all我是否可能需要允许其他范围?我的代码是

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

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

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

我也尝试过与此上传文件

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 :/

推荐答案

该示例脚本如何?该示例的流程如下.

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

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

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

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.

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.

这篇关于如何使用node.js上传OneDrive API文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆