Download file from Dropbox with JavaScript

爱⌒轻易说出口 提交于 2019-12-04 08:18:14

A simple and straightforward solution is using XMLHTTP as follows

function readDropbox(sURL) 
{
    var oRequest = new XMLHttpRequest();
    oRequest.open("GET",sURL,false);
    oRequest.onreadystatechange = function(oEvent) 
    {  
        if (oRequest.readyState === 4) 
        {  
            if (oRequest.status === 200) 
            {  
                console.log(oRequest.responseText)  
            } 
            else  
            {  
                console.log("Error", oRequest.statusText);  
            }  
        } 
    } 
    oRequest.setRequestHeader("User-Agent",navigator.userAgent); 
    try 
    {
        oRequest.send(null)
    } 
    catch (err) 
    {
        alert(err);
    }
    if (oRequest.status == 200) 
    {
        return oRequest.responseText;
    }
    else 
    {
        alert("Error - File not found in Dropbox public folder");
        return null;
    }
}

You do not need to use Dropbox.js to download the file from the link returned by the Chooser. Dropbox.js is a library for connecting the Dropbox Core API, which is separate from the Chooser. The client.readFile function is meant to take a path to a file in an authorized Dropbox account, not a URL to a file as you have it.

Since you already have a direct link to the desired file that doesn't require authentication, you can just directly download it via whatever means is available to your platform. (A simple example might be using curl in your terminal.)

If you want to access the contents of the Dropbox file from your client side javascript code, I suggest you use the server side to get the contents and send them back to the client (using Ajax seems most elegant). It is generally impossible to access the contents of any URL outside the current domain from javascript code (exceptions are references to external javascript code).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!