How can I upload two files to Dropbox from MATLAB and store their shared links in variables file1 and file2?

9 views (last 30 days)
I want to automate the process of uploading two specific files to Dropbox using MATLAB. Once the files are uploaded, I need to retrieve the shared links for each file and save them in two variables: file1 and file2.
This would make my life much easier, as the actual problem I am working on is much larger. I’ve simplified it here to focus on this part, but the solution will be applied to a more complex scenario. Could anyone guide me through the process, including setting up Dropbox API access, authentication, and writing the necessary MATLAB code?
If sample code or a step-by-step explanation is available, it would be greatly appreciated!

Answers (2)

Umar
Umar on 18 Oct 2024

Hi @Muhammad Afaq Zafar ,

After going through your comments, I understand that your goal is to upload the files and retrieve their shared links, which will be stored in two variables: file1 and file2. This automation will streamline your workflow, especially when dealing with more complex tasks. Below is the MATLAB code that accomplishes the task of uploading files to Dropbox and retrieving their shared links.

% Dropbox API Access Token
accessToken = 'YOUR_ACCESS_TOKEN';
% File paths for the files to be uploaded
filePath1 = 'path/to/your/first/file.txt';
filePath2 = 'path/to/your/second/file.txt';
% Upload files to Dropbox
file1 = uploadToDropbox(filePath1, accessToken);
file2 = uploadToDropbox(filePath2, accessToken);
% Display the shared links
disp(['Shared link for file 1: ', file1]);
disp(['Shared link for file 2: ', file2]);
function sharedLink = uploadToDropbox(filePath, accessToken)
    % Get the file name from the file path
    [~, name, ext] = fileparts(filePath);
    dropboxPath = ['/', name, ext]; % Path in Dropbox
      % Read the file content
      fileContent = fileread(filePath);

Fore more information on fileread function, please refer to

https://www.mathworks.com/help/matlab/ref/fileread.html?searchHighlight=fileread&s_tid=srchtitle_support_results_1_fileread

      % Create the HTTP request to upload the file
      url = 'https://content.dropboxapi.com/2/files/upload';
      headers = {
        'Authorization', ['Bearer ', accessToken];
        'Content-Type', 'application/octet-stream';
        'Dropbox-API-Arg', jsonencode(struct('path', dropboxPath, 'mode', 'add', 
         'autorename', true, 'mute', false))
      };
      % Perform the upload
      response = webwrite(url, fileContent, headers{:});
      % Create a shared link for the uploaded file
      sharedLink = createSharedLink(dropboxPath, accessToken);
    end
function sharedLink = createSharedLink(dropboxPath, accessToken)
  % Create the HTTP request to create a shared link
  url = 'https://api.dropboxapi.com/2/sharing/.  
 create_shared_link_with_settings';
  headers = {
      'Authorization', ['Bearer ', accessToken];
      'Content-Type', 'application/json'
  };
  body = jsonencode(struct('path', dropboxPath, 'settings', 
  struct('requested_visibility', 'public')));

For more information on jsonencode function, please refer to

https://www.mathworks.com/help/matlab/ref/jsonencode.html

    % Perform the request to create a shared link
    response = webwrite(url, body, headers{:});

For more information on webwrite function, please refer to https://www.mathworks.com/help/matlab/ref/webwrite.html?s_tid=doc_ta

    % Extract the URL from the response
    sharedLink = response.url;
  end

In the above code snippet, the accessToken variable holds your Dropbox API access token. You need to generate this token from the Dropbox App Console. The filePath1 and filePath2 variables specify the local paths of the files you wish to upload and uploadToDropbox function handles the file upload process. It constructs the necessary HTTP request to upload the file to Dropbox using the API endpoint for file uploads. The function also creates a shared link for the uploaded file by calling the createSharedLink function which sends a request to the Dropbox API to create a shared link for the uploaded file. It returns the URL of the shared link. Finally, the shared links for both files are displayed in the MATLAB command window.

Important tips

  • Make sure that you replace 'YOUR_ACCESS_TOKEN' with your actual Dropbox API access token.
  • The file paths must be correctly specified to point to the files you wish to upload.
  • This code assumes that the files are text files. If you are uploading different file types, ensure that the content type is appropriately set.

Hope this helps.

Please let me know if you have any further questions.


Sameer
Sameer on 18 Oct 2024
  3 Comments
Umar
Umar on 19 Oct 2024

Hi @Muhammad Afaq Zafar,

The error message indicates a "Bad Request" response from the Dropbox API, which suggests that there may be issues with how the request is being formed or executed. In order to resolve this issue, click link below

     <https://www.dropbox.com/login?   
   cont=https%253A%252F%252Fwww.dropbox.com%252Fdevelopers%252Fapps       https://www.dropbox.com/login?      cont=https%3A%2F%2Fwww.dropbox.com%2Fdevelopers%2Fapps>

Create a new app by selecting "Dropbox API" and "App folder". Generate an access token and keep it safe, as it will be needed for authentication in your MATLAB code. Make sure upload function correctly formats the request and handles errors gracefully. Below is an updated version of your uploadToDropbox function, along with a new function to generate shared links after successful uploads.

function [file1Link, file2Link] =   
A uploadFilesToDropbox(accessToken, file1Path, file2Path)
  % Upload two files to Dropbox and return their shared links.
    % Upload first file
    output1 = uploadToDropbox(accessToken, file1Path);
    file1Link = createSharedLink(accessToken, output1.id);
    % Upload second file
    output2 = uploadToDropbox(accessToken, file2Path);
    file2Link = createSharedLink(accessToken, output2.id);
  end
function output = uploadToDropbox(dropboxAccessToken, dataFile)
  % Check if input file exists
  if ~exist(dataFile, 'file')
      error('Input file was not found: %s', dataFile);
  end
    % Read file contents
    fid = fopen(dataFile, 'rb');
    data = fread(fid, '*uint8')';  % Read as binary for correct 
    encoding
    fclose(fid);
    % Generate the custom header
    [~, remoteFName, remoteExt] = fileparts(dataFile);
    headerFields = {
        'Authorization', ['Bearer ', dropboxAccessToken];
        'Dropbox-API-Arg', sprintf('{"path": "/%s%s", "mode": 
         "add", "autorename": true}', remoteFName, remoteExt);
        'Content-Type', 'application/octet-stream'
    };
    % Set options for webwrite
    opt = weboptions('MediaType', 'application/octet-stream', ...
                     'RequestMethod', 'post', ...
                     'HeaderFields', headerFields);
    % Upload the file
    try
        tempOutput =    
         webwrite('https://content.dropboxapi.com/2/files/upload', 
         data,opt);
        output = tempOutput;
    catch ME
        error('Unable to upload file: %s', ME.message);
    end
  end
function link = createSharedLink(dropboxAccessToken, fileId)
  % Create a shared link for the uploaded file.
    url ='https://api.dropboxapi.com/2/sharing/
    create_shared_link_with_settings';
    % Construct request body
    body = jsonencode(struct('path', fileId));
    headerFields = {
        'Authorization', ['Bearer ', dropboxAccessToken];
        'Content-Type', 'application/json'
    };
    opt = weboptions('RequestMethod', 'post', ...
                     'HeaderFields', headerFields);
    try
        response = webwrite(url, body, opt);
        link = response.url;  % Extract shared link from response
    catch ME
        error('Unable to create shared link: %s', ME.message);
    end
  end

So, in the above code snippet, uploadFilesToDropbox Function takes the Dropbox access token and paths of two files to upload them sequentially. It returns the shared links for both files. However, uploadToDropbox modified Function reads the binary content of a specified file and uploads it to Dropbox. It constructs the necessary headers for authentication and content type.After successfully uploading a file, this createSharedLink creates a shared link for it using its ID. Reading files in binary mode (rb) ensures that the data is Before deploying this solution in a larger project context, test each component individually with various files to ensure reliability.

By following these steps and using the provided code, you should be able to automate your Dropbox uploads successfully and manage shared links effectively within your MATLAB environment.

Hope this helps.

Sign in to comment.

Categories

Find more on File Operations in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!