Cla*_*lva 5 javascript jquery dropbox dropbox-api dropbox-sdk-js
我试图将文件直接上传到dropbox [来自浏览器/网络应用程序],代码API上的"uploadFile"函数需要在服务器上上传文件,这给我带来了麻烦,因为我不想要任何要上传到我的服务器并从那里到dropbox的文件.
$f = fopen("test.jpg", "rb"); // requires file on server
$result = $dbxClient->uploadFile("test.jpg", dbx\WriteMode::add(), $f);
fclose($f);
Run Code Online (Sandbox Code Playgroud)
试过这个https://github.com/dropbox/dropbox-js失望地说没有明确的文档,文档部分的许多链接都被破坏了.
我需要将文件上传到我的帐户,客户端无需登录到Dropbox.
任何指针都会非常感激.寻找Ajax/JavaScript方法.
更新
我尝试了以下内容,但没有来自Dropbox的回复
HTML
<input type="file" name="file" id="file" onchange="doUpload(event)">
Run Code Online (Sandbox Code Playgroud)
JavaScript的
var doUpload = function(event){
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var arrayBuffer = reader.result;
$.ajax({
url: "https://api-content.dropbox.com/1/files_put/auto/uploads/" + input.files[0].name,
headers: {
Authorization: 'Bearer ' + MyAccessToken,
contentLength: file.size
},
crossDomain: true,
crossOrigin: true,
type: 'PUT',
contentType: input.files[0].type,
data: arrayBuffer,
dataType: 'json',
processData: false,
success : function(result) {
$('#uploadResults').html(result);
}
});
}
reader.readAsArrayBuffer(input.files[0]);
}
Run Code Online (Sandbox Code Playgroud)
小智 6
Dropbox 刚刚发布了一个博客,其中包含有关如何执行此操作的说明。你可以在https://blogs.dropbox.com/developers/2016/03/how-formio-uses-dropbox-as-a-file-backend-for-javascript-apps/找到它(完全披露,我写了博文。)
以下是上传文件的方法。
/**
* Two variables should already be set.
* dropboxToken = OAuth token received then signing in with OAuth.
* file = file object selected in the file widget.
*/
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(evt) {
var percentComplete = parseInt(100.0 * evt.loaded / evt.total);
// Upload in progress. Do something here with the percent complete.
};
xhr.onload = function() {
if (xhr.status === 200) {
var fileInfo = JSON.parse(xhr.response);
// Upload succeeded. Do something here with the file info.
}
else {
var errorMessage = xhr.response || 'Unable to upload file';
// Upload failed. Do something here with the error.
}
};
xhr.open('POST', 'https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'Bearer ' + dropboxToken);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify({
path: '/' + file.name,
mode: 'add',
autorename: true,
mute: false
}));
xhr.send(file);
Run Code Online (Sandbox Code Playgroud)
然后要从保管箱下载文件,请执行此操作。
var downloadFile = function(evt, file) {
evt.preventDefault();
var xhr = new XMLHttpRequest();
xhr.responseType = 'arraybuffer';
xhr.onload = function() {
if (xhr.status === 200) {
var blob = new Blob([xhr.response], {type: ’application/octet-stream’});
FileSaver.saveAs(blob, file.name, true);
}
else {
var errorMessage = xhr.response || 'Unable to download file';
// Upload failed. Do something here with the error.
}
};
xhr.open('POST', 'https://content.dropboxapi.com/2/files/download');
xhr.setRequestHeader('Authorization', 'Bearer ' + dropboxToken);
xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify({
path: file.path_lower
}));
xhr.send();
}
Run Code Online (Sandbox Code Playgroud)
FileSaver 和 Blob 在较旧的浏览器上不起作用,因此您可以向它们添加解决方法。
正如其他答案所指出的那样,每个上传或下载文件的会话都需要访问 Dropbox 令牌。将其他人的令牌发送给用户是一个安全问题,因为拥有令牌将使他们能够完全控制 Dropbox 帐户。完成这项工作的唯一方法是让每个人通过 Dropbox 进行身份验证并获得自己的令牌。
在Form.io,我们已经在我们的平台中实现了身份验证和上传/下载。这使得使用 Dropbox 作为文件后端构建 Web 应用程序变得非常容易。
非常感谢@smarx 的指点,我得以找到最终的解决方案。
此外,我还添加了一些额外的功能,例如监听上传进度,以便可以向用户显示上传进度百分比。
超文本标记语言
<input type="file" name="file" id="file" onchange="doUpload(event)">
Run Code Online (Sandbox Code Playgroud)
JavaScript
var doUpload = function(event){
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var arrayBuffer = reader.result;
var arrayBufferView = new Uint8Array( arrayBuffer );
var blob = new Blob( [ arrayBufferView ], { type: input.files[0].type } );
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL( blob );
$.ajax({
url: "https://api-content.dropbox.com/1/files_put/auto/YourDirectory/" + input.files[0].name,
headers: {
'Authorization':'Bearer ' +YourToken,
'Content-Length':input.files[0].size
},
crossDomain: true,
crossOrigin: true,
type: 'PUT',
contentType: input.files[0].type,
data: arrayBuffer,
dataType: 'json',
processData: false,
xhr: function()
{
var xhr = new window.XMLHttpRequest();
//Upload progress, litsens to the upload progress
//and get the upload status
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = parseInt( parseFloat(evt.loaded / evt.total) * 100);
//Do something with upload progress
$('#uploadProgress').html(percentComplete);
$('#uploadProgressBar').css('width',percentComplete+'%');
}
}, false);
},
beforeSend: function(){
// Things you do before sending the file
// like showing the loader GIF
},
success : function(result) {
// Display the results from dropbox after upload
// Other stuff on complete
},
});
}
reader.readAsArrayBuffer(input.files[0]);
}
Run Code Online (Sandbox Code Playgroud)
你使用 PUT 方法,因为我们唯一的目标是上传文件,根据我对各种资源(StackOverflow和zacharyvoase)的研究,put 方法可以流式传输大文件,它的设计是将文件放在指定的 URI 上,如果文件存在必须更换文件。PUT 方法不能移动到指定 URL 之外的其他 URL。
风险
在客户端使用访问令牌会面临风险,需要采取高安全措施来屏蔽令牌。但是现代 Web 开发工具(例如浏览器控制台、Firebug 等)可以监视您的服务器请求并可以查看您的访问令牌。