How to CREATE new files in SharePoint 2010 Document Libraries with JavaScript and AJAX
Writing and downloading text files to a SharePoint server with JavaScript and AJAX

How to CREATE new files in SharePoint 2010 Document Libraries with JavaScript and AJAX

This is file creation, not a file upload.

Working with a Production Reporting System, there are many instances where you need to create new documents in SharePoint 2010 Document Libraries. While there are many ways to upload documents, I hadn't come across any easy ways to write new files from scratch. I looked around the net, and put together a few articles, and I was able to put together a simple working demo. This demo creates a new text file at the click of a button. In this example, the text file is an HTML document with the extension of .xls, so it opens with Excel. First, within SharePoint, we need to set up our file structure.

This is what the SiteAssets/Scripts directory looks like.

This is what the SitePages/DocumentWriter directory looks like.


Set up for this demo

  1. Create a Web Part Page.
  2. Create an HTML page.
  3. Create A JavaScript file.
  4. In the Web Part Page, add a Content Editor Web Part, and point it to the HTML page.
  5. In the HTML page:
  6. Add a reference to JQuery
  7. Add a reference to your JavaScript File.
  8. Add a or something to initiate the action.

Here is the code for the SitePages/DocumentWriter/DocumentWriter.html page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Document Writer</title>
    <script type="text/javascript" src="/sites/Thunder/Monkey/SandBox/SiteAssets/Scripts/jquery-1.10.2.js"></script>
    <script type="text/javascript" src="/sites/Thunder/Monkey/SandBox/SiteAssets/Scripts/clsDocumentWriter.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            clsDocumentWriter.btnCreateDocument_OnClick(clsDocumentWriter.ControlArray.btnCreateDocument);
        });
    </script>
</head>

<body>

    <div id="dvExport">
        <h1>How to write documents in SharePoint 2010</h1>
        <h2>This is file creation, not a file upload.</h2>
        <p>
            Working with a Production Reporting System, there are many instances where you need to create new documents in SharePoint 2010 Document Libraries. While there are many ways to upload documents, I hadn't come across any easy ways to write new files from scratch. I looked around the net, and put together a few articles, and I was able to put together a simple working demo. This demo creates a new text file at the click of a button. In this example, the text file is an HTML document with the extension of .xls, so it opens with Excel. First, within SharePoint, we need to set up our file structure.
        </p>
        <dl>
            <dt>Set up for this demo</dt>
            <dd>
                <ol>
                    <li>Create a Web Part Page.</li>
                    <li>Create an HTML page.</li>
                    <li>Create A JavaScript file.</li>
                    <li>
                        In the Web Part Page, add a Content Editor Web Part, and point it to
                        the HTML page.
                    </li>
                    <li>
                        In the HTML page:
                        <ol>
                            <li>Add a reference to JQuery</li>
                            <li>Add a reference to your JavaScript File.</li>
                            <li>
                                Add a <input type="button" id="btnCreateDocument" value="Button" />
                                or something to initiate the action.
                            </li>
                        </ol>
                    </li>
                </ol>
            </dd>
        </dl>
    </div>

    <table id="tblExport">
        <tr>
            <td>Cupcake ipsum dolor sit amet I love. Bear claw candy canes cheesecake. Biscuit liquorice halvah I love bear claw marshmallow candy canes powder. Danish soufflé carrot cake I love candy canes. Gummies carrot cake tootsie roll sesame snaps apple pie cookie dragée jujubes. Powder marshmallow I love liquorice danish cotton candy cake pudding sugar plum. Fruitcake candy canes I love chocolate I love toffee donut. Gummi bears chupa chups marzipan chocolate oat cake. Ice cream gummi bears cookie ice cream icing cotton candy croissant marshmallow. Marzipan candy oat cake chocolate bar. Toffee bonbon sweet cookie topping biscuit I love macaroon chocolate bar. Icing toffee sweet roll chupa chups gummies.</td>
        </tr>
    </table>

</body>

</html>

 
  

Here is the code for the SiteAssets/Scripts/clsDocumentWriter.js file

var clsDocumentWriter = {
    ControlArray: { btnCreateDocument: '#btnCreateDocument' }
    , createRandomWord: function (length) {
        var consonants = 'bcdfghjklmnpqrstvwxyz',
            vowels = 'aeiou',
            rand = function (limit) {
                return Math.floor(Math.random() * limit);
            },
            i, word = '', length = parseInt(length, 10),
            consonants = consonants.split(''),
            vowels = vowels.split('');
        for (i = 0; i < length / 2; i++) {
            var randConsonant = consonants[rand(consonants.length)],
                randVowel = vowels[rand(vowels.length)];
            word += (i === 0) ? randConsonant.toUpperCase() : randConsonant;
            word += i * 2 < length - 1 ? randVowel : '';
        }
        return word;
    }
    , ajax: function (soapEnv, complete) {
        $.ajax({
            url: "https://MySharePointSite.com/sites/Potato/Monkey/Thunder/_vti_bin/copy.asmx"
            , beforeSend: function (xhr) {
                xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/CopyIntoItems");
            }
            , type: "POST"
            , dataType: "xml"
            , data: soapEnv
            , complete: complete
            , contentType: "text/xml; charset=\"utf-8\""
        });
    }
    , getSoapEnv: function myfunction(SourceUrl, DestinationUrl, encodedString) {
        var soapEnv = "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> \
                    <soap:Body>\
                        <CopyIntoItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>\
                            <SourceUrl>" + SourceUrl + "</SourceUrl>\
                                <DestinationUrls>\
                                    <string>" + DestinationUrl + "</string>\
                                </DestinationUrls>\
                                <Fields>\
                                    <FieldInformation Type='Text' DisplayName='Title' InternalName='Title' Value='Test' />\
                                </Fields>\
                            <Stream>" + encodedString + "</Stream>\
                        </CopyIntoItems>\
                    </soap:Body>\
                </soap:Envelope>";
        return soapEnv;
    }
    , createFile: function (filePath, DestinationUrl, resultpanel, set_url, fileContent) {
        var encodedString = Base64.encode(fileContent);
        var decodedString = Base64.decode(encodedString);

        var RandomNumber = Math.floor((Math.random() * 1000) + 1);

        var soapEnv = clsDocumentWriter.getSoapEnv(filePath, DestinationUrl, encodedString);
        var complete = function () {
            location.href(DestinationUrl);
        }
        clsDocumentWriter.ajax(soapEnv, complete);
    }
    , getfileContent: function (tblData) {
        var fileContent = '';
        fileContent = fileContent + '<!DOCTYPE html>';
        fileContent = fileContent + '<html xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">';
        fileContent = fileContent + '<head>';
        fileContent = fileContent + '<meta charset="utf-8" />';
        fileContent = fileContent + '<title>Document Creation in SharePoint 2010</title>';
        fileContent = fileContent + '<meta name=ProgId content=Excel.Sheet>';
        fileContent = fileContent + '<meta http-equiv=Content-Type content="text/html; charset=windows-1252">';
        fileContent = fileContent + '<meta name=Generator content="Microsoft Excel 15">';
        fileContent = fileContent + '</head>';
        fileContent = fileContent + '<body>';
        fileContent = fileContent + '<Div id = "tblData">';
        fileContent = fileContent + '<Table>';
        fileContent = fileContent + $(tblData).html();
        fileContent = fileContent + '</Table>';
        fileContent = fileContent + '</Div>';
        fileContent = fileContent + '</body>';
        fileContent = fileContent + '</html>';
        return fileContent;
    }
	, Export: function (filePath, DestinationUrl, set_url, tblExport, resultpanel) {
	    var fileContent = clsDocumentWriter.getfileContent(tblExport);
	    clsDocumentWriter.createFile(filePath, DestinationUrl, resultpanel, set_url, fileContent);
	}
    , btnCreateDocument_OnClick: function (btnCreateDocument) {
        $(btnCreateDocument).click(function () {
            var set_url = clsDocumentWriter.createRandomWord(5) + ".xls";
            var tblExport = '#tblExport';
            var resultpanel = clsDocumentWriter.ControlArray.btnCreateDocument;
            var DestinationUrl = "https://MySharePointSite.com/sites/Potato/Monkey/SandBox/Shared%20Documents/" + set_url;
            var filePath = "/sites/Potato/Monkey/SandBox/SiteAssets/Scripts/Untitled_1.txt"//  A source file is required, even if you are writing out a new document.
            clsDocumentWriter.Export(filePath, DestinationUrl, set_url, tblExport, resultpanel);
        });
    }
};

var Base64 = {
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
	, encode: function (e) {
	    var t = "";
	    var n, r, i, s, o, u, a;
	    var f = 0;
	    e = Base64._utf8_encode(e);
	    while (f < e.length) {
	        n = e.charCodeAt(f++);
	        r = e.charCodeAt(f++);
	        i = e.charCodeAt(f++);
	        s = n >> 2;
	        o = (n & 3) << 4 | r >> 4;
	        u = (r & 15) << 2 | i >> 6;
	        a = i & 63;
	        if (isNaN(r)) {
	            u = a = 64
	        } else if (isNaN(i)) {
	            a = 64
	        }
	        t = t + this._keyStr.charAt(s) + this._keyStr.charAt(o) + this._keyStr.charAt(u) + this._keyStr.charAt(a)
	    }
	    return t
	}
	, decode: function (e) {
	    var t = "";
	    var n, r, i;
	    var s, o, u, a;
	    var f = 0;
	    e = e.replace(/[^A-Za-z0-9+/=]/g, "");
	    while (f < e.length) {
	        s = this._keyStr.indexOf(e.charAt(f++));
	        o = this._keyStr.indexOf(e.charAt(f++));
	        u = this._keyStr.indexOf(e.charAt(f++));
	        a = this._keyStr.indexOf(e.charAt(f++));
	        n = s << 2 | o >> 4;
	        r = (o & 15) << 4 | u >> 2;
	        i = (u & 3) << 6 | a;
	        t = t + String.fromCharCode(n);
	        if (u != 64) {
	            t = t + String.fromCharCode(r)
	        }
	        if (a != 64) {
	            t = t + String.fromCharCode(i)
	        }
	    }
	    t = Base64._utf8_decode(t);
	    return t
	}
	, _utf8_encode: function (e) {
	    e = e.replace(/rn/g, "n");
	    var t = "";
	    for (var n = 0; n < e.length; n++) {
	        var r = e.charCodeAt(n);
	        if (r < 128) {
	            t += String.fromCharCode(r)
	        } else if (r > 127 && r < 2048) {
	            t += String.fromCharCode(r >> 6 | 192);
	            t += String.fromCharCode(r & 63 | 128)
	        } else {
	            t += String.fromCharCode(r >> 12 | 224);
	            t += String.fromCharCode(r >> 6 & 63 | 128);
	            t += String.fromCharCode(r & 63 | 128)
	        }
	    }
	    return t
	}
	, _utf8_decode: function (e) {
	    var t = "";
	    var n = 0;
	    var r = c1 = c2 = 0;
	    while (n < e.length) {
	        r = e.charCodeAt(n);
	        if (r < 128) {
	            t += String.fromCharCode(r);
	            n++
	        } else if (r > 191 && r < 224) {
	            c2 = e.charCodeAt(n + 1);
	            t += String.fromCharCode((r & 31) << 6 | c2 & 63);
	            n += 2
	        } else {
	            c2 = e.charCodeAt(n + 1);
	            c3 = e.charCodeAt(n + 2);
	            t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
	            n += 3
	        }
	    }
	    return t
	}
}
 
  

When you wire it up (be sure to check your file references, because you are using a different server than me), you should get a page that looks like this.

When you click on the button, a new file is created in your document library. That file is an HTML file, with the file extension of ".xls". When the file is saved, the browser is redirected to the newly created file. Because of the file extension, the browser offers the option of opening the file in the proper application. This can be done with Word documents also.

If you try this, and you run into problems with it, feel free to make contact, and I'll take a look at your code.

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics