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?

3 Answers 3

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
    Commented Feb 16, 2022 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
    Commented Mar 28, 2022 at 18:06
0

There is a NodeJS-SharePoint example project for what you are trying to achieve: github.com/drass/node-sharepoint-file-sharing

It uses sppull and spsave, I recommend trying out these modules instead of sp-request.

0

I realize this question is old but this question pointed me in the right direction for solving this issue for myself. The only issue I can see with your code is that you are reading the file using 'utf-8' encoding.

 const file = await fs.readFile(filename);

I also found out that I was missing the "json:false" part of the request as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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