Need to see if your shared folder is taking up space on your dropbox 👨‍💻? Find out how to check here.

Forum Discussion

varunvyas5678's avatar
varunvyas5678
Explorer | Level 3
4 years ago

Error : POST https://content.dropboxapi.com/2/files/upload_session/append_v2 400 (Bad Request)

Getting error while appending blobs to session using 'https://content.dropboxapi.com/2/files/upload_session/append_v2' in Salesforce LWC JS:

 

    uploadFile(event){

        var file = event.target.files[0];
        console.log(file);
        var dropboxToken = 'AccessToken'
        console.log('FileName:'+file.name);


       




        const maxBlob = 8 * 1000 * 1000;
                var workItems = [];
                var offset = 0;
                var sessionID;

                // Slice the file into chunks for upload session
                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) {
                        // Start multipart upload of file
                        return acc.then(function() {
                            return fetch(dbxURL_start, {
                                        "method": "post",
                                        "headers": {
                                        "Authorization" : "Bearer "+dropboxToken,
                                        "Content-Type": "application/octet-stream",
                                        "Dropbox-API-Arg": "{\"close\":false}"
                                        },
                                    "body": blob
                            })
                            .then((response) => {
                                sessionID = response.session_id;
                            })                                      
                            .catch(err => console.log("[ERROR] UPLOAD_SESSION_START : " + err));
                        })
                    } else if (idx < items.length-1) {
                        // Append part to the upload session
                        return acc.then(function(sessionID) {

                            return fetch(dbxURL_append, {
                                        "method": "post",
                                        "headers": {
                                        "Authorization" : "Bearer "+dropboxToken,
                                        "Content-Type": "application/octet-stream",
                                        "Dropbox-API-Arg": "{\"cursor\": {\"session_id\": \"" + sessionID + "\",\"offset\":\"" + (idx * maxBlob) + "\"},\"close\":false}"
                                        },
                                    "body": blob
                            })
                            .then(() => sessionID)
                            .catch(err => console.log("[ERROR] UPLOAD_SESSION_APPEND : " + err));
                        })
                    } else {
                        // Last chunk of data, close upload session
                        return acc.then(function(sessionID) {

                            return fetch(dbxURL_finish, {
                                        "method": "post",
                                        "headers": {
                                        "Authorization" : "Bearer "+dropboxToken,
                                        "Content-Type": "application/octet-stream",
                                        "Dropbox-API-Arg": "{\"cursor\": {\"session_id\": \"" + sessionID + "\",\"offset\":\"" + (file.size - blob.size) + "\"},\"commit\": {\"path\":\"/render/" + filename + "\",\"mode\":{\".tag\":\"add\"}}, \"close\":true}"
                                        },
                                    "body": blob
                            })
                            .then((httpResponse) => {
                                if (httpResponse.ok){
                                    console.log("HTTP RES : OK")
                                    return httpResponse.ok
                                } else {
                                    console.log("HTTP RES : NOT OK")
                                    return !httpResponse.ok
                                }                                  
                            })
                            .catch(err => console.log("[ERROR] UPLOAD_SESSION_FINISH : " + err));
                        })
                    }
                }, Promise.resolve());


                task.then(function(result) {
               
                console.log('result:',result);

            }).catch(function(error) {
                console.error(error);
            });

    }

6 Replies

  • Greg-DB's avatar
    Greg-DB
    Icon for Dropbox Community Moderator rankDropbox Community Moderator
    4 years ago

    Make sure you check the response body itself. It should contain a more specific error indicating what the issue is.

  • varunvyas5678's avatar
    varunvyas5678
    Explorer | Level 3
    4 years ago

    Response for the callout is:
    Error in call to API function "files/upload_session/append:2": The given OAuth 2 access token is malformed.

  • Greg-DB's avatar
    Greg-DB
    Icon for Dropbox Community Moderator rankDropbox Community Moderator
    4 years ago

    That error message indicates that there's an issue with the access token value you're supplying with the API call. Check the access token you're sending and make sure you're using the exact value as it was provided to you by Dropbox. Don't add or remove any characters, make sure there's no stray whitespace, etc. (As a matter of security, do not share any access tokens or refresh tokens here.)

  • varunvyas5678's avatar
    varunvyas5678
    Explorer | Level 3
    4 years ago

    Hi Greg, I looked into it and got to know that am not getting the Session_Id in the response of upload_session/start callout. So I tried hitting it with the following snippet:

                "method": "post",
                "headers": {
                    "Authorization" : "Bearer "+dropboxToken,
                    "Content-Type": "application/octet-stream",
                    "Dropbox-API-Arg": "{\"close\":false}"
                },
            "body": file
            })
            .then((httpResponse) => {
                console.log('Response:',httpResponse);
                if (httpResponse.ok){
                    console.log("HTTP RES : OK")
                    return httpResponse.ok
                } else {
                    console.log("HTTP RES : NOT OK")
                    return !httpResponse.ok
                }                                  
            })
            .catch(err => console.log("[ERROR] UPLOAD_SESSION_FINISH : " + err));

    And even after status code of 200 am not getting any Session_Id, This is the response am getting:
    1. Response {type: 'cors', url: 'https://content.dropboxapi.com/2/files/upload_session/start', redirected: false, status: 200, ok: true, …}
      1. body: ReadableStream
      2. bodyUsed: false
      3. headers: Headers {}
      4. ok: true
      5. redirected: false
      6. status: 200
      7. statusText: "OK"
      8. type: "cors"
      9. url: "https://content.dropboxapi.com/2/files/upload_session/start"
      10. [[Prototype]]: Response
        1. arrayBuffer: ƒ arrayBuffer()
        2. blob: ƒ blob()
          1. length: 0
          2. name: "blob"
          3. arguments: (...)
          4. caller: (...)
          5. [[Prototype]]: ƒ ()
          6. [[Scopes]]: Scopes[0]
        3. body: (...)
        4. bodyUsed: (...)
        5. clone: ƒ clone()
          1. length: 0
          2. name: "clone"
          3. arguments: (...)
          4. caller: (...)
          5. [[Prototype]]: ƒ ()
          6. [[Scopes]]: Scopes[0]
        6. formData: ƒ formData()
          1. length: 0
          2. name: "formData"
          3. arguments: (...)
          4. caller: (...)
          5. [[Prototype]]: ƒ ()
          6. [[Scopes]]: Scopes[0]
        7. headers: (...)
        8. json: ƒ json()
        9. ok: (...)
        10. redirected: (...)
        11. status: (...)
        12. statusText: (...)
        13. text: ƒ text()
        14. type: (...)
        15. url: (...)
        16. constructor: ƒ Response()
        17. Symbol(Symbol.toStringTag): "Response"
        18. get body: ƒ body()
        19. get bodyUsed: ƒ bodyUsed()
        20. get headers: ƒ headers()
        21. get ok: ƒ ok()
        22. get redirected: ƒ redirected()
        23. get status: ƒ status()
        24. get statusText: ƒ statusText()
        25. get type: ƒ type()
        26. get url: ƒ url()

     

  • Здравко's avatar
    Здравко
    Legendary | Level 20
    4 years ago

    varunvyas5678 wrote:

    Hi Greg, I looked into it and got to know that am not getting the Session_Id in the response of upload_session/start callout. ...


    Hi varunvyas5678,

    Once succeeds, the session id is within response body as JSON text. Fetch it out  from there. 😉 Take a look here (for example). Why don't you use the official SDK? 🤷

    Hope this helps.

  • Greg-DB's avatar
    Greg-DB
    Icon for Dropbox Community Moderator rankDropbox Community Moderator
    4 years ago

    varunvyas5678 I see you're getting back a response with a 200 status code, which indicates the call succeeded, so as Здравко said, you'll need to read out the JSON from the response body to get the session ID. We do recommend using an official SDK whenever possible, as it will do most of the work for you. You can find the instructions for the official Dropbox JavaScript SDK here, for instance.

About Dropbox API Support & Feedback

Node avatar for Dropbox API Support & Feedback
Find help with the Dropbox API from other developers.

The Dropbox Community team is active from Monday to Friday. We try to respond to you as soon as we can, usually within 2 hours.

If you need more help you can view your support options (expected response time for an email or ticket is 24 hours), or contact us on X, Facebook or Instagram.

For more info on available support options for your Dropbox plan, see this article.

If you found the answer to your question in this Community thread, please 'like' the post to say thanks and to let us know it was useful!