How to use a document as a Sharepoint list

Copper Contributor

 

Hello,

By working with sharepoint REST APIs, there was a problem storing a file in a folder. Indeed, we tried to manipulate the document as a Sharepoint list by following the Microsoft documentation Using folders and files with REST : https://docs.microsoft.com/fr-fr/sharepoint/dev/sp-add-ins/working-with-folders-and-files-with-rest.

 

We tried to manipulate the file as a list element, but this generates an error : To add an item to a document library, use SPFileCollection.Add ()

 

The goal is to add a file with several columns: name, content and other column

 

How can we proceed?

2 Replies

A few things:

 

1. Can you show us your code so we can see how you're trying to add the file? The documentation you're reading shows you how to do it directly via REST, but the error message you're getting seems like it's coming from CSOM. In order to add a file to a document library directly using REST, you would make a POST request:

url: http://site url/_api/web/GetFolderByServerRelativeUrl('/Folder Name')/Files/add(url='a.txt',overwrite=true)
method: POST
body: "Contents of file"
Headers:
Authorization: "Bearer " + accessToken
X-RequestDigest: form digest value
content-length:length of post body

 The body should be your file as a Blob or ArrayBuffer.

 

2. In order to change the metadata of the file, you need to then GET that file as a List Item object and change metadata on the List Item.

 

3. I would skip dealing that altogether and just use PnPJS, which would allow you to both upload the File then change the List Item metadata nicely by chaining a .then() and using the file.getItem() method.

https://github.com/pnp/pnpjs/blob/dev/packages/sp/docs/files.md#setting-associated-item-values

 

Essentially your code would look like this (where myFile is an ArrayBuffer or Blob):

import { sp } from "@pnp/sp";

sp.web.getFolderByServerRelativeUrl("/sites/<your site>/<your doc lib>/<your folder>/").files.add(myFile.name, myFile, true).then(f => {
    
    f.file.getItem().then(item => {

        item.update({
            Title: "A Title",
            OtherField: "My Other Value",
YetAnotherField: 5 }); }); }); 

 

First, Thank You for your reply.

Here is my code :

$urlSpo = $this->container->getParameter('repos_share_point'); 

$authCtx = new AuthenticationContext($urlSpo);

$authCtx->acquireTokenForUser($sharePointParameters['userName'], $sharePointParameters['password']); //authenticate $ctx = new ClientContext($urlSpo, $authCtx); $web = $ctx->getWeb();

$list = $web->getLists()->getByTitle($this->container->getParameter('folder_share_point'));

//init List resource

$itemProperties = array('Title' => $documentName . ".pdf", '__metadata' => array('type' => 'SP.Data.TasksListItem'), 'Company' => $company);

$item = $list->addItem($itemProperties); $ctx->executeQuery();

To add columns to the file, I tried to manipulate it as a list item.

But this doesn't work.