The Salesforce REST API can be used to download a single file from the ContentVersion object. First, you will need to obtain a session id from the API. This will provide you with an auth token that you can use to make the request for the file. Fortunately, the library jsforce will do all that work for us
Let’s see an example about how to download a ContentVersion file through the Salesforce rest API
In the following code, we are going to download a Salesforce File (ContentVersion) that we already know that it is an image file (.png). If you don’t know the file type you will need to run an extra call to get that information and generate the file name accordingly with its extension.
The endpoint that gets the body of the file (binary) it’s /services/data/v51.0/sobjects/ContentVersion/{recordId}/VersionData
const jsforce = require('jsforce');
const https = require('https');
const fs = require('fs');
const conn = new jsforce.Connection();
const userName = '*******';
const password = '*******';
const securityToken = '*********';
const fileId = '0684W00000BzWohQAF';
const fullFileName = '/Users/andrescanavesi/sf.png';
conn.login(userName, password+securityToken, function(err, res) {
if (err) { return console.error(err); }
console.log(conn.accessToken);
console.log(conn.instanceUrl);
// logged in user property
console.log("User ID: " + res.id);
console.log("Org ID: " + res.organizationId);
downloadFile(conn);
});
function downloadFile(conn) {
const options = {
hostname: 'myinstance-dev-ed.my.salesforce.com',
port: 443,
path: '/services/data/v51.0/sobjects/ContentVersion/'+fileId+'/VersionData',
method: 'GET',
headers: {
'Content-Type': 'application/octet-stream',
'Authorization': 'OAuth '+conn.accessToken
}
}
https.get(options, (resp) => {
let data = '';
// A chunk of data has been received.
resp.on('data', (chunk) => {
console.log('chunk');
data += chunk;
fs.appendFile(fullFileName, chunk, function (err) {
if (err) throw err;
console.log('chunk updated');
});
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
console.log('data downloaded');
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
In the above code we use a native module https for Node.js to make the request. Of course you can use any other module such as axios or node-fetch