Dropbox 直接从浏览器上传文件

Dropbox direct upload files from browser

我正在尝试 [从浏览器/Web 应用程序] 直接将文件上传到 Dropbox,代码 API 上的 "uploadFile" 函数需要上传文件到服务器,这给我带来麻烦,因为我不想将任何文件上传到我的服务器并从那里上传到保管箱。

$f = fopen("test.jpg", "rb"); // requires file on server
$result = $dbxClient->uploadFile("test.jpg", dbx\WriteMode::add(), $f);
fclose($f);

尝试了这个 https://github.com/dropbox/dropbox-js 失望地说没有明确的文档,文档部分的许多链接都已损坏。

我需要将文件上传到我的帐户,客户不需要登录 dropbox。

任何指点将不胜感激。寻找 Ajax / JavaScript 方法。

更新

我尝试了以下方法,但 Dropbox 没有任何响应

HTML

<input type="file" name="file" id="file" onchange="doUpload(event)">

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]);
}

"I need the files to be uploaded to my account and the clients need not login to dropbox."

那么您真的需要上传 server-side。要做到这一点,客户端意味着将访问令牌发送到浏览器,此时您应用程序的任何用户都可以使用该访问令牌对您的帐户执行任何他们想做的事情。 (例如删除所有其他文件,上传他们的私人 DVD collection,等等)

出于安全原因,我强烈建议上传 server-side,您可以在其中对访问令牌保密。

非常感谢@smarx 的指点,我得以找到最终的解决方案。

此外,我还添加了一些额外的功能,例如收听上传进度,以便可以向用户显示上传进度百分比。

HTML

<input type="file" name="file" id="file" onchange="doUpload(event)">

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]);
    }

你使用了 PUT 方法,因为我们唯一的 objective 是上传文件,根据我对各种资源的研究 (Whosebug and zacharyvoase)将文件放在指定的 URI 上,如果文件存在,则必须替换该文件。无法将 PUT 方法移至指定的 URL 以外的其他 URL。

风险

您在客户端使用访问令牌存在风险,需要采取高安全措施来屏蔽令牌。但是像浏览器控制台、Firebug 等现代 Web 开发工具可以监视您的服务器请求并可以看到您的访问令牌。

Dropbox 刚刚 post 发布了一个博客,其中包含有关如何执行此操作的说明。您可以在 https://blogs.dropbox.com/developers/2016/03/how-formio-uses-dropbox-as-a-file-backend-for-javascript-apps/ 找到它(完全公开,我写了博客 post。)

这是上传文件的方法。

/**
 * 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);

然后执行此操作从保管箱下载文件。

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();
}

FileSaver 和 Blob 无法在旧版浏览器上运行,因此您可以为它们添加解决方法。

正如其他答案所指出的,每个上传或下载文件的会话都需要访问保管箱令牌。将其他人的令牌发送给用户是一个安全问题,因为拥有令牌将使他们能够完全控制保管箱帐户。使这项工作有效的唯一方法是让每个人都通过 Dropbox 进行身份验证并获得他们自己的令牌。

Form.io 我们已经在我们的平台中实现了身份验证和 upload/download。这使得使用 Dropbox 作为文件后端构建 Web 应用程序变得非常容易。

upload.html

上传

upload.js

$('#form_wizard_1 .button-submit').click(function () {
      var ACCESS_TOKEN ="Your token get from dropbox";
      var dbx = new Dropbox({ accessToken: ACCESS_TOKEN });
      var fileInput = document.getElementById('files1');
      var file = fileInput.files[0];
      res=dbx.filesUpload({path: '/' + file.name, contents: file})
      .then(function(response) {
      var results = document.getElementById('results');
      results.appendChild(document.createTextNode('File uploaded!'));
      res=response;
      console.log(response);
    })
    .catch(function(error) {
       console.error(error);
    });
}

到目前为止给出的答案没有使用 Dropbox javascript SDK,我认为这可能是最好的解决方法。在此处查看 link:

https://github.com/dropbox/dropbox-sdk-js/blob/master/examples/javascript/upload/index.html

其中提供了一个示例,该示例取决于是否已下载 SDK。 (编辑:在玩过 SDK 之后,我意识到它会创建一个 POST 请求,类似于该线程中已接受的答案。但是,流行的答案忽略了 sdk 在实际调用之前进行的 OPTIONS 预检调用POST)

我可能还要补充一点,dropbox sdk 示例中没有显示的是您可以将 blob 对象上传到 dropbox;例如,如果您想从 canvas 中动态提取图像并上传它们,并且不想上传通过文件上传输入从文件系统中选择的内容,这将很有用。

这是我描述的场景的一个简短示例:

//code below after having included dropbox-sdk-js in your project.  
//Dropbox is in scope!
var dbx = new Dropbox.Dropbox({ accessToken: ACCESS_TOKEN });
//numerous stack overflow examples on creating a blob from data uri
var blob = dataURIToBlob(canvas.toDataUrl());
//the path here is the path of the file as it will exist on dropbox.
//should be unique or you will get a 4xx error
dbx.filesUpload({path: `unq_filename.png`, contents: blob})