2

I need to upload file to Dropbox with axios. Here is my code:

const uploadToExternalService = async function uploadToExternalService(token, content) {
        try {
            let res = await axios({
                url: 'https://api-content.dropbox.com/1/files_put/auto/'+'file_name',
                method: 'put',
                // timeout: 8000,
                headers: {
                    Authorization: 'Bearer ' + token,
                    'Content-Type': 'text/plain',
                    body: content
                }
            })
            if(res.status == 200){
                // test for status you want, etc
                console.log(res.status)
            }
            if(res.status == 400){
                console.log(res)
            }
            return res.data
        }
        catch (err) {
            console.error(err);
        }
    }

uploadToExternalService(SECRET_KEY, req.file).then(res => console.log(res));

I'm getting error Request failed with status code 400

1

3 Answers 3

2

Eventually I managed to find a solution using dropbox-v2-api. Hopefully this answer will provide a helpful code example for other community members although the solution was implemented w/o axios

import dropboxV2Api from "dropbox-v2-api";
import fs from "fs";

    // authentication
    const dropbox = dropboxV2Api.authenticate({
        token: DROPBOX_SECRET_KEY
    });

    //configuring parameters
    const params = Object.freeze({
        resource: 'files/upload',
        parameters: {
            path: '/file_name.docx'
        },
        readStream: fs.createReadStream(filePath)
        // filePath: path to the local file that we want to upload to Dropbox
    });

    let dropboxPromise = new Promise(function(resolve, reject) {
        dropbox(params, function(err, result) {
            if (err) {
                reject(err);
            } else {
                resolve(result);
            }
        });
    });

    await dropboxPromise.then(function (resultObj) {
        console.log("fileUpload_OK")
    }).catch(function(err){
        console.log(err.message)
    });

1
  • For all others who are stranded here. This solution does not seem to work for files larger than 150MB. Everything above that can be uploaded using streams. Commented Dec 10, 2020 at 10:16
0

You are using dropbox v1 APIs which are officially retired. Why not use v2?

For your problem, try sending the body outside of headers

headers: {
  Authorization: 'Bearer ' + token,
  'Content-Type': 'text/plain'
},
body: content

corrected code:

const uploadToExternalService = async function uploadToExternalService(token, content) {
        try {
            let res = await axios({
                url: 'https://api-content.dropbox.com/1/files_put/auto/'+'file_name',
                method: 'put',
                // timeout: 8000,
                headers: {
                    Authorization: 'Bearer ' + token,
                    'Content-Type': 'text/plain'
                },
                body: content
            })
            if(res.status == 200){
                // test for status you want, etc
                console.log(res.status)
            }
            if(res.status == 400){
                console.log(res)
            }
            return res.data
        }
        catch (err) {
            console.error(err);
        }
    }

uploadToExternalService(SECRET_KEY, req.file).then(res => console.log(res));
1
  • SpiritOfDragon, you forgot to change the url in your response. The v2 url suppose to be as following: https://api-content.dropbox.com/2/files/upload/. Unfortunately it doesn't help much. Still getting 400
    – IgorM
    Commented Apr 18, 2020 at 15:57
0

The Issue

The example cURL from the Dropbox documentation is:

curl -X POST https://content.dropboxapi.com/2/files/upload \
    --header "Authorization: Bearer " \
    --header "Dropbox-API-Arg: {\"path\": \"/Homework/math/Matrices.txt\",\"mode\": \"add\",\"autorename\": true,\"mute\": false,\"strict_conflict\": false}" \
    --header "Content-Type: application/octet-stream" \
    --data-binary @local_file.txt

--data-binary means the /upload endpoint requires the file to be send as binary data. In Axios, it seems the only way to do this is with the FormData() interface.

But, using the FormData() interface requires using Content-Type: multipart/form-data. The /upload endpoint requires Content-Type: application/octet-stream.

Therefore, I do not think uploading using Axios is possible in this situation.

The Alternative Solution

dropbox-v2-api is not an official API for Dropbox and there's no explanation I could find for uploading files more than 150MB. So, instead, I would use dropbox-sdk-js. The example they give for /upload is:

function uploadFile() {
        
      const UPLOAD_FILE_SIZE_LIMIT = 150 * 1024 * 1024;
      var ACCESS_TOKEN = document.getElementById('access-token').value;
      var dbx = new Dropbox.Dropbox({ accessToken: ACCESS_TOKEN });
      var fileInput = document.getElementById('file-upload');
      var file = fileInput.files[0];
      
      
      if (file.size < UPLOAD_FILE_SIZE_LIMIT) { // File is smaller than 150 Mb - use filesUpload API
        dbx.filesUpload({path: '/' + file.name, contents: file})
          .then(function(response) {
            var results = document.getElementById('results');
            var br = document.createElement("br");
            results.appendChild(document.createTextNode('File uploaded!'));
            results.appendChild(br);
            console.log(response);
          })
          .catch(function(error) {
            console.error(error);
          });
      } else { // File is bigger than 150 Mb - use filesUploadSession* API
        const maxBlob = 8 * 1000 * 1000; // 8Mb - Dropbox JavaScript API suggested max file / chunk size

        var workItems = [];     
      
        var offset = 0;

        while (offset < file.size) {
          var chunkSize = Math.min(maxBlob, file.size - offset);
          workItems.push(file.slice(offset, offset + chunkSize));
          offset += chunkSize;
        } 
          
        const task = workItems.reduce((acc, blob, idx, items) => {
          if (idx == 0) {
            // Starting multipart upload of file
            return acc.then(function() {
              return dbx.filesUploadSessionStart({ close: false, contents: blob})
                        .then(response => response.session_id)
            });          
          } else if (idx < items.length-1) {  
            // Append part to the upload session
            return acc.then(function(sessionId) {
             var cursor = { session_id: sessionId, offset: idx * maxBlob };
             return dbx.filesUploadSessionAppendV2({ cursor: cursor, close: false, contents: blob }).then(() => sessionId); 
            });
          } else {
            // Last chunk of data, close session
            return acc.then(function(sessionId) {
              var cursor = { session_id: sessionId, offset: file.size - blob.size };
              var commit = { path: '/' + file.name, mode: 'add', autorename: true, mute: false };              
              return dbx.filesUploadSessionFinish({ cursor: cursor, commit: commit, contents: blob });           
            });
          }          
        }, Promise.resolve());
        
        task.then(function(result) {
          var results = document.getElementById('results');
          results.appendChild(document.createTextNode('File uploaded!'));
        }).catch(function(error) {
          console.error(error);
        });
        
      }
      return false;
    } 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.