How to upload a document with values related to document properties in to document set at same time using Javascript object model

Hi,
      Problem Description: Need to upload a document with values related to document properties using custom form in to document set using JavaScript Object Model.
    Kindly let me know any solutions.
Thanks
Razvi444

The following code shows how to use REST/Ajax to upload a document to a document set.
function uploadToDocumentSet(filename, content) {
appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
var restSource = appweburl +
"/_api/SP.AppContextSite(@target)/web/GetFolderByServerRelativeUrl('/restdocuments/testds')/files/add(url='" + filename + "',overwrite=true)?@target='" + hostweburl + "'";
var dfd = $.Deferred();
$.ajax(
'url': restSource,
'method': 'POST',
'data': content,
processData: false,
timeout:1000000,
'headers': {
'accept': 'application/json;odata=verbose',
'X-RequestDigest': $('#__REQUESTDIGEST').val(),
"content-length": content.byteLength
'success': function (data) {
var d = data;
dfd.resolve(d);
'error': function (err,textStatus,errorThrown) {
dfd.reject(err);
return dfd;
Then when this code returns you can use the following to update the metadata of the new document.
function updateMetadataNoVersion(fileUrl) {
appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
var restSource = appweburl +
"/_api/SP.AppContextSite(@target)/web/GetFolderByServerRelativeUrl('/restdocuments/testds')/files/getbyurl(url='" + fileUrl + "')/listitemallfields/validateupdatelistitem?@target='" + hostweburl + "'";
var dfd = $.Deferred();
$.ajax(
'url': restSource,
'method': 'POST',
'data': JSON.stringify({
'formValues': [
'__metadata': { 'type': 'SP.ListItemFormUpdateValue' },
'FieldName': 'Title',
'FieldValue': 'My Title2'
'bNewDocumentUpdate': true,
'checkInComment': ''
'headers': {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose',
'X-RequestDigest': $('#__REQUESTDIGEST').val()
'success': function (data) {
var d = data;
dfd.resolve(d);
'error': function (err) {
dfd.reject(err);
return dfd;
Blog | SharePoint Field Notes Dev Tools |
SPFastDeploy | SPRemoteAPIExplorer

Similar Messages

  • How to create a Document Set in SharePoint 2013 using JavaScript Client Side Object Model (JSOM)?

    Hi,
    The requirement is to create ""Document Sets in Bulk" using JSOM. I am using the following posts:-
    http://blogs.msdn.com/b/mittals/archive/2013/04/03/how-to-create-a-document-set-in-sharepoint-2013-using-javascript-client-side-object-model-jsom.aspx
    http://social.msdn.microsoft.com/Forums/sharepoint/en-US/1904cddb-850c-4425-8205-998bfaad07d7/create-document-set-using-ecma-script
    But, when I am executing the code, I am getting error "Cannot read property 'DocumentSet' of undefined "..Please find
    below my code. I am using Content editor web part and attached my JS file with that :-
    <div>
    <label>Enter the DocumentSet Name <input type="text" id="txtGetDocumentSetName" name="DocumentSetname"/> </label> </br>
    <input type="button" id="btncreate" name="bcreateDocumentSet" value="Create Document Set" onclick="javascript:CreateDocumentSet()"/>
    </div>
    <script type="text/javascript" src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"> </script>
    <script type="text/javascript">
       SP.SOD.executeFunc('sp.js','SP.ClientContext','SP.DocumentSet','SP.DocumentManagement.js',CreateDocumentSet);
    // This function is called on click of the “Create Document Set” button. 
    var ctx;
    var parentFolder;
    var newDocSetName;
    var docsetContentType;
    function CreateDocumentSet() {
        alert("In ClientContext");
        var ctx = SP.ClientContext.get_current(); 
        newDocSetName = $('#txtGetDocumentSetName').val(); 
        var docSetContentTypeID = "0x0120D520";
        alert("docSetContentTypeID:=" + docSetContentTypeID);
        var web = ctx.get_web(); 
        var list = web.get_lists().getByTitle('Current Documents'); 
        ctx.load(list);
        alert("List Loaded !!");
        parentFolder = list.get_rootFolder(); 
        ctx.load(parentFolder);
        docsetContentType = web.get_contentTypes().getById(docSetContentTypeID); 
        ctx.load(docsetContentType);
        alert("docsetContentType Loaded !!");
        ctx.executeQueryAsync(onRequestSuccess, onRequestFail);
    function onRequestSuccess() {       
        alert("In Success");
        SP.DocumentSet.DocumentSet.create(ctx, parentFolder, newDocSetName, docsetContentType.get_id());
        alert('Document Set creation successful');
    // This function runs if the executeQueryAsync call fails.
    function onRequestFail(sender, args) {
        alert("Document Set creation failed" + + args.get_message());
    Please help !!
    Vipul Jain

    Hello,
    I have already tried your solution, however in that case I get the error - "UncaughtSys.ArgumentNullException: Sys.ArgumentNullException:
    Value cannot be null.Parameter name: context"...
    Also, I tried removing SP.SOD.executeFunc
    from my code, but no success :(
    Kindly suggest !!!
    Vipul Jain

  • Unable to update rating (rating column) on host document using JavaScript Object Model API inside sharepoint hosted apps

    Hi Everyone,
    We are developing SharePoint hosted apps for Office 365, for that we are going
    to implement document rating functionality inside Sharepoint app. The host web contain document library (“Documents”) and from apps we need to rate each document. The rating functionality working fine with CQWP in team site  using
    JavaScript Object Model API.
    But the same code is not working inside apps and giving error:-
    If we are using app context than error will be:-
    "List does not exist.
    The page you selected contains a list that does not exist.  It may have been deleted by another user."
    And for Host context than error will be:-
    "Unexpected response data from server."
    Please help on this
    Please see below code..
    'use strict';
    var web, list, listItems, hostUrl, videoId, output = "";
    var videoLibrary = "Documents";
    var context, currentContext;
    var lists, listID;
    var list, parentContext;
    var scriptbase;
    (function () {
        // This code runs when the DOM is ready and creates a context object which is 
        // needed to use the SharePoint object model
        $(document).ready(function () {
            hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
            context = SP.ClientContext.get_current();      
            SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);
        function sharePointReady() {
            scriptbase = hostUrl + "/_layouts/15/";
            // Load the js files and continue to the successHandler
            $.getScript(scriptbase + "SP.Runtime.js", function () {
                $.getScript(scriptbase + "SP.js", function () {
                    $.getScript(scriptbase + "SP.Core.js", function () {
                        $.getScript(scriptbase + "reputation.js", function () {
                            $.getScript(scriptbase + "sp.requestexecutor.js", execCrossDomainRequest);
        //Query list from hostweb
        function execCrossDomainRequest() {       
            //Load the list from hostweb
            parentContext = new SP.AppContextSite(context, hostUrl);
            web = parentContext.get_web();
            list = web.get_lists().getByTitle(videoLibrary);
            context.load(list, 'Title', 'Id');
            var camlQuery = new SP.CamlQuery();
            camlQuery.set_viewXml('<View><Query><OrderBy><FieldRef Name="Modified" Ascending="FALSE"/></OrderBy></Query><RowLimit>1</RowLimit></View>');
            listItems = list.getItems(camlQuery);        
            context.load(listItems);
            context.executeQueryAsync(onQuerySucceeded, onQueryFailed);
        //Process the image library
        function onQuerySucceeded() {       
            var lstID = list.get_id();
            var ctx = new SP.ClientContext(hostUrl);       
            var ratingValue = 4;
            EnsureScriptFunc('reputation.js', 'Microsoft.Office.Server.ReputationModel.Reputation', function() {      
            Microsoft.Office.Server.ReputationModel.Reputation.setRating(ctx, lstID, 1, ratingValue);       
            ctx.executeQueryAsync(RatingSuccess, RatingFailure);
        function onQueryFailed(sender, args) {
            alert('Failed' + args.get_message());
        function failed(sender, args) {
            alert("failed because:" + args.get_message());
        function RatingSuccess() {
            alert('rating set');
            //displaystar();
        function RatingFailure(sender, args) {
            alert('Rating failed : : ' + args.get_message());
        //Gets the query string paramter
        function getQueryStringParameter(paramToRetrieve) {
            var params;
            params = document.URL.split("?")[1].split("&");
            for (var i = 0; i < params.length; i = i + 1) {
                var singleParam = params[i].split("=");
                if (singleParam[0] == paramToRetrieve) return singleParam[1];
    Thanks & Regards
    Sanjay 
    Thank you in advance! :-)
          

    Hi,
    According to your post, my understanding is that you want to update list column in SharePoint hosted apps using JavaScript Client Object Model.
    Based on the error message, it seems not retrieve the list object in context. I suggest you debug the code step by step using Internet Explorer Developer Tools to
    find the problem.
    Here are some demos about using JavaScript Client Object Model in SharePoint hosted app:
    http://blogs.msdn.com/b/officeapps/archive/2012/09/04/using-the-javascript-object-model-jsom-in-apps-for-sharepoint.aspx
    http://sharepoint.stackexchange.com/questions/55334/how-to-access-list-in-sharepoint-hosted-app
    http://www.dotnetcurry.com/showarticle.aspx?ID=1028
    Best regards
    Zhengyu Guo
    TechNet Community Support

  • How to load several documents at the same time (PWA 2013)

    Hi
    In 2010 there was an option for that:
    In the document library of a project site, I want to load several documents at the same time.
    How can we do that in PWA 2013 ?
    Thanks

    Robert,
    Here is a video taht might help. if the Dragging does not work, you could also use the regular Explorer method.
    https://www.youtube.com/watch?v=7n4fP3YWYI4
    Cheers,
    Prasanna Adavi, Project MVP
    Blog:
      Podcast:
       Twitter:   
    LinkedIn:
      

  • IF_IXML : How can i add encoding with value UTF-8 to the document object??

    Hi
    i want to create a xml file with the following content:
    <?xml version="1.0" encoding="UTF-8"?>
    <OpenSearchDescription xmlns="http://...."> 
    </OpenSearchDescription>
    i did this with the if_ixml interface and rendered the content in a file 'D:\usr\sap\IFD\DVEBMGS01\log\TEST_out.xml
    <?xml version="1.0"?>
    <OpenSearchDescription xmlns="http://...."> 
    </OpenSearchDescription>
    BUT the document attribut(?) encoding="UTF-8"?> is missing!
    How can i add encoding with value UTF-8 to the document object?? it should look like:
    <?xml version="1.0" encoding="UTF-8"?>
    *here is my coding.
    TYPE-POOLS: ixml.
    CLASS cl_ixml DEFINITION LOAD.
    DATA: lo_ixml           TYPE REF TO if_ixml,
          lo_streamfactory  TYPE REF TO if_ixml_stream_factory,
          lo_document       TYPE REF TO if_ixml_document,
          lo_parent         TYPE REF TO if_ixml_element,
          lo_ostream        TYPE REF TO if_ixml_ostream,
          lo_renderer       TYPE REF TO if_ixml_renderer,
         lv_rc           TYPE i.
    lo_ixml = cl_ixml=>create( ).
    lo_streamfactory = lo_ixml->create_stream_factory( ).
    lo_document = lo_ixml->create_document( ).
    lo_parent = lo_document->create_simple_element( name   = 'OpenSearchDescription'  "root node
                                                    parent = lo_document ).
    lo_parent->set_attribute_ns( name   =  'xmlns'
                                 value  = 'http://....' ).
    *rausrendern in file
    lo_ostream = lo_streamfactory->create_ostream_uri( system_id = 'D:\usr\sap\IFD\DVEBMGS01\log\TEST_out.xml' ).
    lo_renderer = lo_ixml->create_renderer( ostream  = lo_ostream
                                            document = lo_document ).
    lv_rc = lo_renderer->render( ).
    Thanks for help
    Britta

    Use the following code:
    set an document encoding
      l_encoding = l_ixml->create_encoding( character_set = 'UTF-8'
                                            byte_order = if_ixml_encoding=>co_none ).
      l_success  = l_ostream->set_encoding( encoding = l_encoding ).
    create a xml renderer
      l_renderer = l_ixml->create_renderer( document = l_doc ostream  = l_ostream ).

  • How to upload the documents like PDF, EXCEL and WORD

    Hi,
    I am working on UI, I am tracking the COREMODS data using this UI. My requirement is need to maintain the related documents also in database using this UI. I think SLM system have that functionality. If any one know about this functionality, explain about
    How to upload the documents into database.
    How to maintain this documents in database.
    Is there any standard methods/function modules to upload this documents ( I am not asking about content of document, I am expecting about total file).
    i.e. I want to maintain the all core mod related test cases and other documents in SAP database.
    How to handle this functionality?        
    Rayudu

    Hi Rayudu,
    For office documents we can use [Business Document Service|http://help.sap.com/saphelp_nw70/helpdata/EN/3d/90a9371c726343e10000009b38f842/frameset.htm]
    Cheers,
    Jose.

  • How to change 'Modified By' column value when a new file is uploaded in SharePoint 2013 using Client Object Model?

    I want to change 'Modified By' column value of a file that is being uploaded using Client Object Model in SharePoint 2013. The problem is that the version of the file is changing. Kindly help me. The code that I am using is:
    using (System.IO.Stream fileStream = System.IO.File.OpenRead(m_strFilePath))
        Microsoft.SharePoint.Client.File.SaveBinaryDirect(m_clientContext, str_URLOfFile, fileStream, true);
        Microsoft.SharePoint.Client.File fileUploaded = m_List.RootFolder.Files.GetByUrl(str_URLOfFile);
        m_clientContext.Load(fileUploaded);
        m_clientContext.ExecuteQuery();
        User user1 = m_Web.EnsureUser("User1");
        User user2 = m_Web.EnsureUser("User2");
        ListItem item = fileUploaded.ListItemAllFields;
        fileUploaded.CheckOut();
        item["UserDefinedColumn"] = "UserDefinedValue1";
        item["Title"] = "UserDefinedValue2";
        item["Editor"] = user1;
        item["Author"] = user2;
        item.Update();
        fileUploaded.CheckIn(string.Empty, CheckinType.OverwriteCheckIn);
        m_clientContext.ExecuteQuery();

    Hi talib2608,
    Chris is correct for this issue, when calling update using ListItem.update method, it will increase item versions, using SystemUpdate and UpdateOverwriteVersion will update the list item overwrite version.
    these two methods are not available in CSOM/REST, only server object model is available for this.
    Thanks,
    Qiao Wei
    TechNet Community Support

  • How do you apply a master page to multiple documents at the same time?

    How do you apply a master page to multiple documents at the same time?

    Hi friends,
    Thank you for trying to help me out.
    Let me explain it a bit to remove the ambiguity.
    I have 10 documents nested under a book. Each of these documents have 'n' number of pages. I want to apply my custom made master page "First" to the first page of all these 10 documents in one go. The remaining pages of the documents have to be in default "Right" master page format. How will I do it?
    I tried selecting all the documents and importing the formats from another document with the custom made "First" master page. The master page format is getting imported but the first page of all the documents still remain with the default "Right" master page format.
    I think now my question is more clear...

  • Does anyone knows a way to work with various Pages documents at the same time, for example with a system of tabs to switch directly from one document to the other?

    Hello everyone,
    Working with numerous Apple Pages documents at the same time, I am looking for an efficient solution to switch faster from one document to the other. Integrating all them in a single framework, for exemple by switching from one to the other with a system of tabs would be of great help. Does anyone knows if such a possibility exists?
    Thanks in advance,
    Jean-Baptiste

    jbp- wrote:
    Thanks. It works and is very efficient. Not as much as a real system of tabs, but is allows to switch very fast between different documents. Only regret I would have is that it doesn't work with a document which is on full page mode. But that's already very helpful!
    You're very welcome but Peggy really gave you the answer already. 
    With regard to the full screen apps, I don't think Apple have yet worked out how to make them elegantly coexist with other apps.  The closest you can get is the four finger swipe gestures you may use on a trackpad if you have one (Mission Control and App Exposé).
    In fact nowadays I use the App Exposé (four finger swipe down gesture) more often than I use Command-Accent to move between documents in the same app (when not in full screen).  It also as the advantage of showing you thumbnails of recently opened documents below the ones already open within the app.  If you haven't tried it, I suggest you give it a whirl.
    I can't remember now but I think the four finger gestures are not enabled by default and you must switch them on in System Preferences > Trackpad > More Gestures. 

  • How can 2 user edit 1 word document at the same time

    hi,
    in office 2013 professional plus, can 2 user edit 1 word document at the same time?

    Hi,
    As far as I know, multiple users can not edit Word file in the same time directly. Could you give me your demand?
    Please check the two follows workarounds if they are helpful:
    http://blogs.msdn.com/b/johnmullinax/archive/2010/04/19/co-authoring-how-two-people-can-edit-one-word-2010-doc-at-the-same-time.aspx?Redirected=true
    http://www.ehow.com/how_7229904_allow-word-document-same-time.html
    Please Note: Since the web site is not hosted by Microsoft, the link may change without notice. Microsoft does not guarantee the accuracy of this information.
    Regards,
    George Zhao
    TechNet Community Support
    Hi
    thank you; its worked.
    I'm so excited about this; thank you again.

  • How do I delete multiple documents at the same time

    How do I delete several or multiple documents at the same time.  Do I have to delete each one individully?

    You can select multiple adjacent files or folders by clicking on the first one then shift-click on the last one.  Multiple non-adjacent files or folders can be selected one at a time by command clicking on each one.  Click on any selected file or folder then drag/drop to trash.

  • How can I visualize 2 documents at the same time

    How can I visualize 2 documents at the same time?
    thanks

    Adobe Reader on mobile devices allows to view ONE document at a time.

  • How do I change font in the whole document at the same time?

    How do I change font in the whole document at the same time?

    Menu > View > Show Styles Drawer
    Menu > Help > Pages User Guide
    Download and read page 27 on creating and using Styles, which is done largely by example ie you make the text what you want then save it as a Style to be applied wherever you want in the document from the Styles Drawer.
    http://www.freeforum101.com/iworktipsntrick/viewtopic.php?t=180&mforum=iworktips ntrick
    Peter

  • Can anybody explain how to print multiple copies of different documents at the same time as at the moment I have to open each individually and press print

    Can anybody explain how to print multiple copies of different documents at the same time as at the moment I have to open each individually and press print

    is this a windows in bootcamp question ?

  • How to Enable Ratings on SharePoint List using Client Object Model for Office 365 SharePoint Site.

    How to Enable Ratings on SharePoint List using Client Object Model code for Office 365 SharePoint Site.
    Thanks in Advance
    Rajendra K

    Hi Rajendra,
    here you are the code and the blog, let me know if this helps
    using (ClientContext ctx = new ClientContext(https://yourSiteUrl))
    Web w = ctx.Web;
    List l = w.Lists.GetByTitle("yourListName");
    ctx.Load(l, info => info.Id);
    ctx.ExecuteQuery();
    string ListID = l.Id.ToString();
    Microsoft.Office.Server.ReputationModel.Reputation.SetRating(ctx, ListID, 1, 5);
    ctx.ExecuteQuery();
    http://blogs.technet.com/b/speschka/archive/2013/07/08/how-to-use-csom-with-ratings-in-sharepoint-2013.aspx
    Kind Regards, John Naguib Technical Consultant/Architect MCITP, MCPD, MCTS, MCT, TOGAF 9 Foundation

Maybe you are looking for