I want to Download a file with a API Call. First I thought it would be a good idea to download it from the sharelink by changing the query parameter ?dl to 1 and then use axios to just get that and save the file buffer. This worked for the most files, but sometimes the downloaded PDFs where broken and could'nt be opened.
So I tried the download endpoint "https://content.dropboxapi.com/2/files/download" without the SDK.
const axios = require('axios');
let config = {
'method': 'POST',
'url': 'https://content.dropboxapi.com/2/files/download',
'headers': {
'Dropbox-API-Select-User': 'MYAPISELECTUSER',
'Dropbox-API-Path-Root': '{".tag": "namespace_id", "namespace_id": "MYNAMESPACE"}',
'Dropbox-API-Arg': '{"path":"/MY Folder/myfile.PDF"}',
'Authorization': 'Bearer MYBEARERTOKEN'
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
I get the error: "Response failed with a 400 code"
When I try this in Postman it works but the same code on my nodejs server gives me status 400 codes. No further explanations error messages nothing.
Then I tried with the Dropbox SDK and 'isomorphic-fetch' instead of axios.
const fs = require("fs");
var Dropbox = require('dropbox').Dropbox;
var fetch = require('isomorphic-fetch');
const dlFile = async () => {
try {
var dbx = new Dropbox({ accessToken: 'MYBEARERTOKEN', fetch: fetch });
const response = await dbx.filesDownload( {path: '/My Folder/myfilename.PDF' })
console.log(JSON.stringify(response));
fs.createWriteStream("test.pdf",response.data);
} catch (err) {
console.log(`${err} ${err.message}`);
return err;
}
};
const main = async function () {
await dlFile();
};
main();
Same result Status code 400.
Finally I also tried the request module
const fs = require("fs");
const request = require('request')
const dlFile = async () => {
try {
var options = {
'method': 'POST',
'url': 'https://content.dropboxapi.com/2/files/download',
'headers': {
'Dropbox-API-Select-User': 'MYSELECTUSERID',
'Dropbox-API-Path-Root': '{".tag": "namespace_id", "namespace_id": "MYNAMESPACE"}',
'Dropbox-API-Arg': '{"path":"/My Folder/myfilename.PDF"}',
'Authorization': 'Bearer MYTOKEN'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
//console.log(response)
fs.writeFileSync("myfilename.pdf", response.body);
});
} catch (err) {
console.log(`${err} ${err.message}`);
return err;
}
};
const main = async function () {
await dlFile();
};
main();
The buffer from response.body looks promising:
"%PDF-1.4
%
1 0 obj
<<
/SM 0.001
/Type/ExtGState
>>
endobj
2 0 obj
<<
/Width 1521
/ColorSpace/DeviceCMYK
/Height 357
/Subtype/Image
/Type/XObject
/Length 2171988
/BitsPerComponent 8
>>
stream
and so on...."
But when I open the PDF file it has a frame with the right format but it's empty just white.
What am I missing whats the recommended way?
Why is it working in Postman but not on my NodeJs server?