I'm trying to send a file to a SharePoint folder using the sp-request module. I can upload a .txt file and it opens correctly. But when uploading .docx files, the file becomes corrupted.
My collection of .docx files resides in a node server.
I've tried sending the file buffer obtained from fs.readFile(filename)
, as well as the encoded content obtained from fs.readFile(filename, "utf8")
.
Either way, the file is uploaded and arrives at the destination folder, but it cannot be opened. The error is: "This file can't be opened for editing", and it won't open in the desktop as well.
Here's my controller function in express, where spr
is sp-request:
async function uploadFile(req, res, next) {
try {
const filename = "filename.docx"
const file = await fs.readFile(filename, "utf8");
const url = siteURL + `_api/web/GetFolderByServerRelativeUrl('FolderName')/Files/add(url='${filename}',overwrite=true)`;
const digest = await spr.requestDigest(siteURL);
const result = await spr.post(url, {
headers: {
'X-RequestDigest': digest,
},
body: file,
json: false,
});
} catch (error) {
next(error);
}
}
What am I missing?