4

I need to add a new item in a document library using JSOM. The document library also possesses custom columns.

I am able to upload file but unable to get proper method to add the custom column values to the library using JSOM.

Following is the code that I have used for updating:

function receivedBinary() {
  clientContext = new SP.ClientContext.get_current();
  parentList = clientContext.get_web().get_lists().getByTitle("Lib_MasterDataDetails");
  fileCreateInfo = new SP.FileCreationInformation();
  fileCreateInfo.set_url(file.name);
  fileCreateInfo.set_overwrite(true);
  fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
  var arr = convertDataURIToBinary(this.result);
  for (var i = 0; i < arr.length; ++i) {
      fileCreateInfo.get_content().append(arr[i]);
   }
  newFile = parentList.get_rootFolder().get_files().add(fileCreateInfo);
  clientContext.load(newFile);
  clientContext.executeQueryAsync(function (newFile) {
  var myListItem = newFile.get_listItemAllFields();
  myListItem.set_item("ClientLegalName", "NewValue");
  myListItem.update();
  clientContext.executeQueryAsync(function (sender, args) {
         console.log("Item updated");
     }, genericFailHandler);
  }, genericFailHandler);
}
3

You'll need to upload the file using the SP.FileCreationInformation object, you can write to the list item that corresponds to the file by calling <file>.get_listItemAllFields()

When you use get_listItemAllFields() you'll have a regular list item object that you can use get_item() and set_item() on.

Here is a complete example, you can paste the entire thing into your browser dev tools and run it, just sub the list name in var oList and the field name in myListItem.set_item("Note", "NewValue")

var clientContext = SP.ClientContext.get_current();
var oWebsite = clientContext.get_web();
var oList = oWebsite.get_lists().getByTitle("Documents");

var fileCreateInfo = new SP.FileCreationInformation();
fileCreateInfo.set_url("my new file.txt");
fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
var fileContent = "The content of my new file";

for (var i = 0; i < fileContent.length; i++) {
    fileCreateInfo.get_content().append(fileContent.charCodeAt(i));
}

var newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);
var myListItem = newFile.get_listItemAllFields();
myListItem.set_item("Note", "NewValue")

myListItem.update();
clientContext.executeQueryAsync(function(sender, args) {
    // success on setting item values
    console.log("Item updated");
}, genericFailHandler);

function genericFailHandler(sender, args) { 
    console.log(args.get_message());
}

Edit: I've included a complete working snippet, substitute the string in fileContent for the actual contents of your file and you should be up and running; but this example will create a sample text file then modify one of its list item field values. You can also do this with a single call to executeQueryAsync, so I've updated my answer to show that too.

  • Hi John, Thanks for your reply,i have tried this already and it is not working in this way while we add an item to the document library. I can only be able to upload the file using SP.FileCreationInformation(), but cannot able to update the custom fields. – Sri Sep 23 '15 at 13:42
  • No Issues John, thanks for your feedback and Yes I am new to sharepoint. In my project I have a scenario where I am facing this issue. I tried various wys to add the custom fields but I cannot..:( Could you please help me on this? – Sri Sep 23 '15 at 14:02
  • Hi John, i tried like what u mentioned but it not updating, in listitem creation we use item.update(), in the same manner i used here once assigned the value with set_item(), but its showing item.update is not a function – Sri Sep 23 '15 at 14:42
  • Thank you so much I tried as you told,still not working, its throwing an exception,"newFile.get_listItemAllFields(); is not a function"... – Sri Sep 24 '15 at 7:30
  • @Sri updated to include an entire working example that you can paste into your browser tools – John-M Sep 24 '15 at 11:45
1

What you want is not easy to explain and long.

I recommend you to use REST API instead JSOM. JSOM can upload file up to 1.5M according MSDN.

As I say the solution is long and if you want to, you can visit this post, is in Spanish and written by me just a few minutes ago as an answer to your problem.

The function is a little long

function GuardarArchivosAcciones(archivo) {
    var getFile = getFileBuffer(archivo);
    getFile.done(function(arrayBuffer) {
        var doUpload = uploadDocumentAcciones(arrayBuffer, archivo.name);
        doUpload.done(function(file, status, xhr) {
            var getItem = getListItemDocument(file.d.ListItemAllFields.__deferred.uri);
            getItem.done(function(listItem
            , status, xhr) {
                var doGetListItemEntityTypeFullName = getListItemEntityTypeFullNameAcciones();
                doGetListItemEntityTypeFullName.done(function(archivo, status, xhr) {
                    var itemMetadata = {
                            '__metadata': {
                                'type': archivo.d.ListItemEntityTypeFullName
                            },
                            'AccionId': (data)
                    };

                    jQuery.ajax({
                        url: listItem.d.__metadata.uri,
                        data: JSON.stringify(itemMetadata),
                        type: 'POST',
                        contentType: 'application/json;odata=verbose',
                        headers: {
                            'X-HTTP-Method': 'MERGE',
                            'X-RequestDigest': $("#__REQUESTDIGEST").val(),
                            'Accept': 'application/json;odata=verbose',
                            'IF-MATCH': '*'
                        },
                        success: function(item) { 
                            Alert('Documento subido exitosamente');
                        },
                        error: function(err) {
                            Alert('Falló la subida de los archivos');
                        },
                        complete: function(item) { }
                    });
                });
            });
        });
    });
}

Upload files REST

-1

Try this code.

byte[] content = Encoding.Unicode.GetBytes("file_content");

ClientContext ctx = new ClientContext(new Uri("http://your_site/"));
List l = ctx.Web.Lists.GetByTitle("Shared Documents");

File f = l.RootFolder.Files.Add(
       new FileCreationInformation() { Url = "File.aspx", Overwrite = true, Content = content }
   );

ListItem item = f.ListItemAllFields;
item["ContentType"] = "Basic Page";

ctx.ExecuteQuery();

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.