Remove custom properties/metadata for an Office document [javascript]

I have this document library on Sharepoint where I have one custom column called Metadata and that is a lookup to another list on my Sharepoint.

When the users download an Office document from this library and then re-upload it we could have the below error message:

There is at least one lookup column that enforces a relationship behavior and contains values that reference one or more non-existent items in the target list.

It’s because the Office documents keep the custom columns from the document library from where they have been downloaded… In that case the file tries to reassign the Metadata with an ID that doesn’t exist anymore… causing this issue!

Because I’m using a homemade interface to upload documents, I’ve been able to pass some code to delete the file’s properties on-the-fly before pushing it into the document library.

To do so, you need JSZip that will permit to unzip the Office document in order to retrieve the file docProps/custom.xml and to change the properties we want before the final upload.

Let’s imagine my page contains an <input type="file">, and that I have already loaded JSZip. Then I use FileReader:

var fileReader = new FileReader();
fileReader.onloadend = function(e) {
  // content is the "arraybuffer" that represents my file
  var content = e.target.result;
  // check the file's extension (here "docx", "xlsx", and "pptx", but we could add more extensions
  var ext=file.name.split(".").slice(-1)[0];
  switch (ext) {
    case "docx":
    case "xlsx":
    case "pptx": {
      // load content in JSZip
      JSZip.loadAsync(content)
      .then(function(zip) {
        // unzip the file that contains metadata/properties
        return zip.file("docProps/custom.xml").async("text")
        .then(function(txt) {
          // replace the faulty column
          txt = txt.replace(/name="Metadata"><vt:lpwstr>\d+<\/vt:lpwstr>/,'name="Metadata"><vt:lpwstr><\/vt:lpwstr>');
          // reinject the new file
          zip.file("docProps/custom.xml", txt);
          return zip.generateAsync({type:"arraybuffer"})
        })
      })
      .then(function(content) {
        // do something with your content
        // for example (https://aymkdn.github.io/SharepointPlus/): $SP().list("my_list").createFile({content:content, filename:file.name})
      })
      break;
    }
    default: {
      // for the other files, treat them normally
      // for example (https://aymkdn.github.io/SharepointPlus/): $SP().list("my_list").createFile({content:content, filename:file.name})
    }
  }
}
fileReader.onerror = function(e) {
  console.error(e.target.error);
}
fileReader.readAsArrayBuffer(file);

Laisser un commentaire

Votre adresse e-mail ne sera pas publiée. Les champs obligatoires sont indiqués avec *

*