Search code examples
javascriptjquerydropboxdropbox-apidropbox-sdk-js

Dropbox direct upload files from browser


I am trying to upload files directly to dropbox [from a browser / web application], The "uploadFile" function on the code API needs the file to be uploaded available on the server, this puts me in trouble, because I do not want any files to be uploaded to my server and from there to dropbox.

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

Tried out this https://github.com/dropbox/dropbox-js disappointed to say that there is no clear documentation, many of the links on the documentation part is broken.

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

Any pointers would be really appreciated. looking for Ajax / JavaScript methods.

Update

I have tried the following, but no response from 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]);
}

Solution

  • Many thanks to @smarx with his pointers I was able to reach the final solution.

    Also I have added a few extra features like listening to upload progress so that the users can be showed with the upload progress percentage.

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

    U have used the PUT method as our only objective is to upload files,As per my studies on various resources ( StackOverflow and zacharyvoase ) A put method can stream large files, also its desigend to put files on a specified URI , if file exist the file must be replaced. A PUT method cannot be moved to a different URL other than the URL Specified.

    The Risk

    You are at risk by using access token at client side, there needs to be high security measures to mask the token. But modern Web dev tools like Browser consoles , Firebug etc can monitor your server requests and can see your access token.