1

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?

1 Answer 1

0

You're missing an accept header and a content-length header (ref). I'd guess that's your problem.

But I'd suggest using spsave instead of sp-request. It was written by the same person and uses sp-request under the hood. spsave will handle all the document library idiosyncrasies for you.

2
  • As per this post I don't think I need extra headers. But, I did try your suggestion of adding them manually. No success.
    – Marcos
    Feb 16 at 15:11
  • I ended up using spsave as recommended. However, I cannot accept the above answer as it did not solve/explained the issue I was facing. I DO recommend that people use spsave for saving time.
    – Marcos
    Mar 28 at 18:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.