使用HTTP从dropbox API读取下载的blob

时间:2016-12-21 22:51:16

标签: javascript angularjs dropbox-api

使用Dropbox,您可以通过将URL拖放到Dropbox文件夹中来创建快捷方式。这将保存如下: example of a url in dropbox

使用dropbox中的/2/files/download HTTP API将返回如下所示的XHR响应: raw data returned from dropbox

如何解析此响应,以便您只能获取URL并将其设为可点击链接?

1 个答案:

答案 0 :(得分:0)

以下是Angular 1工厂需要进行的工作。要使用它,您只需从控制器调用downloadFile函数,并提供Dropbox帐户中文件的路径。

 function downloadFile(filePath) {
            if (!filePath) {
                console.error('Cannot download file because no file was specified.');
                return;
            }
            return $q(function(fulfill, reject) {
                $http({
                    url: 'https://content.dropboxapi.com/2/files/download',
                    method: 'POST',
                    headers: {
                        'Authorization': 'Bearer {{access-token-goes-here}}',
                        'Dropbox-API-Arg': `{"path": "${filePath}"}`
                    },
                    responseType: 'blob'
                }).then(
                    results => {
                        // data received from dropbox is binary data saved as a blob
                        // The FileReader object lets web applications asynchronously read the contents of files
                        // https://developer.mozilla.org/en-US/docs/Web/API/FileReader
                        var fileReader = new FileReader();
                         // function will run after successfully reading the file
                        fileReader.onload = function() {
                            var string = this.result; // store the file contents
                            string = encodeURI(string); // get rid of the paragraph return characters
                            var endPosition = string.indexOf('%0D%0A', 32); // find the end of the URL, startPosition is 32
                            var actualURL = string.substring(32, endPosition); // grab only the characters between start and end positions
                            fulfill(actualURL);
                        };
                        fileReader.readAsText(results.data);                           
                    },
                    error => reject(error));
            });
        }