Tuesday, November 4, 2014

How to upload or attach a text file to a SharePoint 2013 list item using REST

How to upload or attach a text file to a SharePoint 2013 list item using REST (text file only)

This post is about attaching a text file to a SharePoint 2013 list item using REST:

1-      Create an html page that should look like below:



<!DOCTYPE html>
<html>
<head lang="en">
    <script src="https://code.jquery.com/jquery-2.1.0.js"></script>
    <script src="uploadFile.js"></script>          
</head>
<body>
        <input id="inputFile" type="file" />
        <input id="upload" type="button" value="Upload" onClick="uploadFile()" />
</body>
</html>


2-      Create a javascript file uploadFile.js that should contain the script below, and update the serverUrl, listName and itemId with the right values:


function uploadFile() {
    var fileInput = $('#inputFile');
    var fullPath= fileInput.val().split('\\');
    var fileName = fullPath[fullPath.length - 1];
               
    var fileData = getFileData(fileInput.val());  
    var serverUrl = "http://myserver-url";
    var listName = "mylist-name";
    var itemId = "1";
               
    var digest = $("#__REQUESTDIGEST").val();
    var restUrl = serverUrl +
                "/_api/web/lists/GetByTitle('" + listName +
                "')/items(" + itemId +
                ")/AttachmentFiles/add(FileName='" + fileName + "')";
                               
    $.ajax({   
                url: restUrl,   
                type: "POST",   
                data: fileData,   
                headers: {"X-RequestDigest": digest}
    });
               
    function getFileData(filePath) {
        var fso = new ActiveXObject("Scripting.FileSystemObject");
        var textStream = fso.OpenTextFile(filePath);
        var fileData = textStream.ReadAll();
        return fileData;
    }
}