如何在使用Javascript Dropbox v2 API时获取传输状态

时间:2017-04-27 20:02:10

标签: javascript dropbox-api

我正在使用Dropbox V2 API for Javascript,我想获得某种类型的状态更新,关于下载或上传的距离 - 到目前为止已传输了多少数据正在上传的文件总大小。

2 个答案:

答案 0 :(得分:0)

Dropbox API v2 JavaScript SDK遗憾的是没有提供跟踪进度信息的方法,但我们认为它是一项功能请求。

答案 1 :(得分:0)

不确定是否要在浏览器 / node.js 方面解决此问题,但以下是如何在节点中执行此操作的示例。 JS

输出:

1% downloaded
5% downloaded
7% downloaded
40% downloaded
54% downloaded
90% downloaded
file downloaded!
100% downloaded

来源:

/**
 * To run example you have to create 'credentials.json' file
 * in current location.
 * 
 * File should contain JSON object, with 'TOKEN' property.
 */

const dropboxV2Api = require('dropbox-v2-api');
const progress = require('progress-stream');
const fs = require('fs');
const path = require('path');

const credentials = JSON.parse(fs.readFileSync(path.join(__dirname, 'credentials.json')));

//set token authentication:
const dropbox = dropboxV2Api.authenticate({
    token: credentials.TOKEN
});

const FILE_PATH = '/dropbox/file.txt';

getSizeByFilePath(FILE_PATH, (err, fileSize) => {
    if(err) return console.log(err);

    getFileStream(FILE_PATH)
        .pipe(getProgresStreamByFileSize(fileSize))
        .pipe(fs.createWriteStream('.' + FILE_PATH));
});

function getProgresStreamByFileSize(fileSize) {
    const progressStream = progress({
        length: fileSize,
        time: 100 // print progress each 100 ms
    });

    progressStream.on('progress', function(progress) {
        const percentage = parseInt(progress.percentage, 10)+'%';
        console.log(`${percentage} downloaded`);
    });

    return progressStream;
}

function getFileStream(filePath) {
    return dropbox({
        resource: 'files/download',
        parameters: {
            path: filePath
        }
    }, (err, result) => {
        if(err) return console.log(err);
        console.log('file downloaded!')
    });
}

function getSizeByFilePath(filePath, cb) {
    dropbox({
        resource: 'files/alpha/get_metadata',
        parameters: {
            'path': filePath,
            'include_media_info': false,
            'include_deleted': false,
            'include_has_explicit_shared_members': false
        }
    }, (err, result) => {
        if(err) return cb(err);
        cb(null, result.size);
    });
}

以下软件包:此示例中使用了progress-streamdropbox-v2-api