google-apps-scriptgoogle-sheetsdropbox

List the names and Urls of the files from folder of dropbox using Google Apps Script


I am trying to list the names and URLs of all files from the folder and subfolders of Dropbox. I found the following code snippet that Cooper proposed in a similar question:

function dbxFileUpload(files) {
  var fldr = DriveApp.getFolderById(getGlobal('GPSTracksFolderId'));
  var fileBlob=UrlFetchApp.fetch(files[0].link).getBlob();
  var file=fldr.createFile(fileBlob);
  var fi=formatFileName(file);
  var fileInfo={'name':fi.getName(),'type':fileBlob.getContentType(), 'size':fileBlob.getBytes(), 'folder':fldr.getName(), 'id':fi.getId()};
  return fileInfo;
}

I am not sure how to use this snippet in my situation. The other sources that could provide solutions are in different languages i.e. Php, Android.

Source 1

Source 2

Source 3

Source 4

I have already created a Dropbox app that provides App Key and App Secret, but due to my beginner skills, I am not sure how to make it work using Google Apps Script. Any guidance would be much appreciated.


Solution

  • I believe your goal is as follows.

    In order to use Dropbox API, it is required to use the access token. In this answer, it supposes that you have already had your valid access token. Please be careful about this.

    In this case, how about the following sample script?

    Sample script:

    In this sample script, the file and folder list are retrieved from your dropbox.

    function myFunction() {
      const accessToken = "###"; // Please set your access token.
      const path = "";
    
      const url = "https://api.dropboxapi.com/2/files/list_folder";
      const res = UrlFetchApp.fetch(url, {
        method: "post",
        headers: { authorization: "Bearer " + accessToken },
        contentType: "application/json",
        payload: JSON.stringify({ path, limit: 2000, recursive: true })
      });
      const obj = JSON.parse(res.getContentText());
      console.log(obj);
    }
    

    Note:

    References:

    Added:

    About the file URL, it seems that {fileId} of https://www.dropbox.com/s/{fileId}/{fileName}?raw=1 is different from the file ID. So, I prepared one more sample script for retrieving the file URL. I think that the following script can retrieve it.

    function getSharedLink() {
      const accessToken = "###"; // Please set your access token.
      const fileId = "###"; // Please set file ID.
    
      const url = "https://api.dropboxapi.com/2/sharing/get_file_metadata";
      const res = UrlFetchApp.fetch(url, {
        method: "post",
        headers: { authorization: "Bearer " + accessToken },
        contentType: "application/json",
        payload: JSON.stringify({ file: fileId })
      });
      const obj = JSON.parse(res.getContentText());
      const sharedLink = obj.preview_url;
    
      console.log(sharedLink);
    }