Introduction
This article explains how to read a file in a Document Library in SharePoint 2013 using CSOM-JavaScript.
Prerequisites
- Ensure you have access to the Office 365 online.
- Ensure the Napa tool is available in your site.
Use the following procedure
- Create an app for SharePoint using Office 365 Tools. If you have missed out on how to create an app in SharePoint 2013, then Click here
- Create a Docment Library and name it “MyDocumentLibrary”. Refer to my article if you want to know how to create a Document Library in SP2013.Click Here
- Create a file by named “MyTextFile”. Click here if you want to know how to create a file in Document Library.
- Click on the Default.aspx page.
- Click on the App.js file.
- Globally declare the content and web objects as shown below.
var context = SP.ClientContext.get_current(); //gets the current context
var web = context.get_web(); //gets the web object
- Now write the function to read a file in a Document Library.
function readFile() {
context.load(web);
context.executeQueryAsync(OnreadServerRelativeURL, readFileFailure);
}
function OnreadServerRelativeURL() {
var fileUrl = web.get_serverRelativeUrl() + "/MyDocumentLibrary/MyTextFile.txt";
$.ajax({
url: fileUrl,
type: "GET"
})
.done(Function.createDelegate(this, readFileSuccess))
.error(Function.createDelegate(this, readFileFailure));
}
- Here in this example we are reading a file in a Document Library.
- Load the web object to get the server realtive URL by calling executeQueryAsync ().
- After getting the server relative URL we need to do a GET operation on file URL using ajax.
function readFileSuccess(data) {
alert(data);
}
function readFileFailure(sender, args) {
debugger;
alert('Failed to read a file. Error:' + args.get_message());
}
- That's it. Now let's start testing.
Testing
- Now to run the app click on the "Play" button that is available towards the left-most corner.
- The app is packaged, deployed, and installed on your Office 365 Site.
- Now you will be able to see the following page.
- Before clicking on Read File button let's navigate to the following URL and check the content in the “MyTextFile”.
Syntax: https://yoursite/DocumentLibraryName
Example: https://mysite/MyDocumentLibrary
- You will be able to see the “MyTextFile” file.
- Click on “…” and click on “Edit”.
- Let's check the content.
- Now click on the Read File button.
- You will be able to see the alert message with the same content. That's it!
Summary
Thus in this article you saw how to read a file in a Document Library in SharePoint 2013 using CSOM-JavaScript.