I'm trying to upload and download files to SharePoint server using sp-request library for Node.js and SHAREPOINT REST API
I am able to handle text files but when it comes to other types of files (images, docx ...) they always end up corrupted.
So I'm wondering, if I should be using other methods to read and write files in my Node.js code.
Upload method :
fs.readFile('file1.png', 'utf8', function (err, file) {
spr.requestDigest('http://vm2008sharepo/')
.then(function (digest) {
return spr.post('http://vm2008sharepo/_api/web/getfolderbyserverrelativeurl(\'Documents\')/Files/Add(url=\'file1.png\')', {
body: file,
headers: {
'X-RequestDigest': digest,
'X-HTTP-Method': 'POST',
'IF-MATCH': '*',
}
})
.then(postResult => {
console.log("File Added");
});
})
.catch(function (err) {
console.log(err.stack);
});
});
Download method :
var file = fs.createWriteStream("file2.odt");
var path = 'file2.odt';
spr.requestDigest('http://vm2008sharepo/')
.then(function (digest) {
spr.get('http://vm2008sharepo/_api/web/GetFileByServerRelativeUrl(\'/Documents/file2.odt\')/$value')
.then(function (response) {
try {
fs.writeFile(path, response.body);
console.log("File Downloaded");
} catch (error) {
console.log(error.stack);
}
});
})
.catch(function (err) {
console.log(err.stack);
});
It turns out my HTTP calls were sending the files in JSON format and I just had to prevent that by adding a line to my code :
return spr.post('http://vm2008sharepo/_api/web/getfolderbyserverrelativeurl(\'Documents\')/Files/Add(url=\'file1.png\')', {
body: file,
json: false,
headers: {
'X-RequestDigest': digest,
'X-HTTP-Method': 'POST',
'IF-MATCH': '*',
}
})