Uploading Files to OneDrive Using Node.js
Upload contents for an item on OneDrive
In order to use this script, please retrieve client id, client secret and refresh token before. About this, you can see the detail information at https://gist.github.com/tanaikech/d9674f0ead7e3320c5e3184f5d1b05cc.
1. Simple item upload
This is for the simple item upload is available for items with less than 4 MB of content. 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 = './sample.zip'; // Filename you want to upload on your local PC
var onedrive_folder = 'SampleFolder'; // Folder name on OneDrive
var onedrive_filename = 'sample.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.getType(file), // When you use old version, please modify this to "mime.lookup(file)",
},
body: f,
}, function(er, re, bo) {
console.log(bo);
});
});
});
2. Resumable item upload
This is for the resumable item upload is provided for large files or when a resumable transfer may be necessary. The detail information is https://dev.onedrive.com/items/upload_large_files.htm.