我正在尝试下载一个文件,到客户端的Webapp本身,使用Dropbox Javascript SDK。
我想说清楚,我只希望下载一个文件到一个文件夹在web应用程序;我理解,出于安全考虑,这实际上可能是不可能的。
我遵循以下文件:
http://dropbox.github.io/dropbox-sdk-js/index.htmlhttp://dropbox.github.io/dropbox-sdk-js/Dropbox.html filesDownload__anchor
这是我的控制器代码:$scope.testDownload = function() {
console.log('Testing Download');
dbx.filesDownload( {path: '/Collorado Springs.jpg'} ) // Just a test file
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(err);
});
};
我可以肯定地看到下载确实发生了,因为它显示在Chrome网络工具中,如下所示:
(我没有足够的信誉来插入多个链接,所以请解释我生成的共享"链接")
https://www.dropbox.com/s/s0gvpi4qq2nw23s/dbxFilesDownload.JPG ? dl = 0
我认为这要么是我缺乏文件下载的知识,要么是我错误地使用了JavaScript。
事先感谢您提供的任何帮助
如果你希望在web应用程序中下载和使用文件,那么最好设置一个后端服务器,并使用它来临时存储内容,当然要征得用户的许可。
要做到这一点,发出一个HTTP请求,然后使用Express通过调用Dropbox服务服务器端来处理请求,然后使用如下代码:
'use strict';
var Dropbox = require('dropbox');
var fs = require('fs');
var path = require('path');
exports.downloadFile = function(token, id, eventID, fileType, callback) {
var dbx = new Dropbox({ accessToken: token }); // creates post-auth dbx instance
dbx.filesDownload({ path: id })
.then(function(response) {
if(response.fileBinary !== undefined) {
var filepath = path.join(__dirname, '../../images/Events/' + eventID + '/' + fileType + '/Inactive/', response.name);
fs.writeFile(filepath, response.fileBinary, 'binary', function (err) {
if(err) { throw err; }
console.log("Dropbox File '" + response.name + "' saved");
callback('File successfully downloaded');
});
}
})
.catch(function(err) {
console.log(err);
callback('Error downloading file using the Dropbox API');
})
}
module.exports = exports;
有一种方法可以在客户端上做到这一点,而不必像公认的答案所建议的那样滚动您自己的服务器实现。
对于其他有此问题的人,您可以使用FileReader
API。
$scope.testDownload = function() {
console.log('Testing Download');
dbx.filesDownload( {path: '/Collorado Springs.jpg'} ) // Just a test file
.then(function(response) {
console.log(response);
const reader = new FileReader();
const fileContentAsText = reader.readAsText(response.result.fileBlob);
reader.onload = (e) => {
console.log({ file: reader.result }); // Logs file content as a string
};
})
.catch(function(error) {
console.log(err);
});
};