I want to upload documents from a web portal to SharePoint programmatically. That is, as user uploads a document it should go directly into SharePoint. I am new to SharePoint and am looking for suggestions/ideas on how to achieve above. Thanks
You have multiple ways of uploading a document, depending on where you code is running. The steps are practically the same.
From the Server Object Model
Use this one if you are working in the SharePoint server side (Web Parts, Event Receivers, Application Pages, etc.)
// Get the context
var context = SPContext.Current;
// Get the web reference
var web = context.Web;
// Get the library reference
var docLib = web.Lists.TryGetList("NAME OF THE LIBRARY HERE");
if (docLib == null)
{
return;
}
// Add the document. Y asume you have the FileStream somewhere
docLib.RootFolder.Files.Add(docLib.RootFolder.Url + "FILE NAME HERE", someFileStream);
From client side code (C#)
Use this one if you are working from a client application that consumes SharePoint services.
// Get the SharePoint context
ClientContext context = new ClientContext("URL OF THE SHAREPOINT SITE");
// Open the web
var web = context.Web;
// Create the new file
var newFile = new FileCreationInformation();
newFile.Content = System.IO.File.ReadAllBytes("PATH TO YOUR FILE");
newFile.Url = "NAME OF THE NEW FILE";
// Get a reference to the document library
var docs = web.Lists.GetByTitle("NAME OF THE LIBRARY");
var uploadFile = docs.RootFolder.Files.Add(newFile);
// Upload the document
context.Load(uploadFile);
context.ExecuteQuery();
From JS using the SharePoint web services
Use this one if you want to upload a document from pages without the server roundtrip:
// Get the SharePoint current Context
clientContext = new SP.ClientContext.get_current();
// Get the web reference
spWeb = clientContext.get_web();
// Get the target list
spList = spWeb.get_lists().getByTitle("NAME OF THE LIST HERE");
fileCreateInfo = new SP.FileCreationInformation();
// The title of the document
fileCreateInfo.set_url("my new file.txt");
// You should populate the content after this
fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
// Add the document to the root folder of the list
this.newFile = spList.get_rootFolder().get_files().add(fileCreateInfo);
// Load the query to the context and execute it (successHandler and errorHandler handle result)
clientContext.load(this.newFile);
clientContext.executeQueryAsync(
Function.createDelegate(this, successHandler),
Function.createDelegate(this, errorHandler)
);
Hope it helps!
Related
I am looking for SharePoint Hosted App Solution which will provision Branding files (JS/CSS/Images) into SharePoint Online/Office 365 environment.
I got a very good article to achive this and tried to implement the same as shown in below link: http://www.sharepointnutsandbolts.com/2013/05/sp2013-host-web-apps-provisioning-files.html
This solution is not working for me and while execution of app, I am getting below error:
Failed to provision file into host web. Error: Unexpected response data from server. Here is the code which is giving me error:
// utility method for uploading files to host web..
uploadFileToHostWebViaCSOM = function (serverRelativeUrl, filename, contents) {
var createInfo = new SP.FileCreationInformation();
createInfo.set_content(new SP.Base64EncodedByteArray());
for (var i = 0; i < contents.length; i++) {
createInfo.get_content().append(contents.charCodeAt(i));
}
createInfo.set_overwrite(true);
createInfo.set_url(filename);
var files = hostWebContext.get_web().getFolderByServerRelativeUrl(serverRelativeUrl).get_files();
hostWebContext.load(files);
files.add(createInfo);
hostWebContext.executeQueryAsync(onProvisionFileSuccess, onProvisionFileFail);
}
Please suggest me, what can be the issue in this code? Or else suggest me another way/reference in which I can Create a SharePoint-Hosted App to provision Branding Files.
Thanks in Advance!
I would use a different method to access host web context as follows:
//first get app context, you will need it.
var currentcontext = new SP.ClientContext.get_current();
//then get host web context
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
var hostcontext = new SP.AppContextSite(currentcontext, hostUrl);
function getQueryStringParameter(param) {
var params = document.URL.split("?")[1].split("&");
var strParams = "";
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == param) {
return singleParam[1];
}
}
}
Here are some references:
https://sharepoint.stackexchange.com/questions/122083/sharepoint-2013-app-create-list-in-host-web
https://blog.appliedis.com/2012/12/19/sharepoint-2013-apps-accessing-data-in-the-host-web-in-a-sharepoint-hosted-app/
http://www.mavention.com/blog/sharePoint-app-reading-data-from-host-web
http://www.sharepointnadeem.com/2013/12/sharepoint-2013-apps-access-data-in.html
Additionally, here is an example of how to deploy a master page, however as you might notice during your testing the method used to get host web context is not working as displayed in the video and you should use the one I described before.
https://www.youtube.com/watch?v=wtQKjsjs55I
Finally, here is a an example of how to deploy branding files through a Console Application using CSOM, if you are smart enough you will be able to convert this into JSOM.
https://channel9.msdn.com/Blogs/Office-365-Dev/Applying-Branding-to-SharePoint-Sites-with-an-App-for-SharePoint-Office-365-Developer-Patterns-and-P
I have a need to retrieve a list of subwebs for a specified user using the client object model. The challenge is that this is being called from a C# web service that is running under the identity of a SharePoint user with access to all the subwebs. Is there a way to filter this list to only return those that belong to a specified user? I only have the username and do not have the password for this account so direct impersonation using NetworkCredential is not going to work.
Pseudo code below:
var clientContext = new ClientContext(siteUrl);
var site = clientContext.Web;
var user = site.CurrentUser;
clientContext.Load(site);
clientContext.Load(user);
clientContext.ExecuteQuery();
var webCollection = site.GetSubwebsForCurrentUser(null);
clientContext.Load(webCollection);
clientContext.ExecuteQuery();
foreach (var web in webCollection)
{
// should I check permissions here?
}
I am trying to create a site in my sharepoint hosted app using Javascript client object model in a SP Online site with a custom template.
Question: Can I do this in a sharepoint hosted app? If so please can you provide some examples.
Here is my code
this.context = SP.ClientContext.get_current();
this.web = context.get_web();
// Build out the WebCreationInformation for the new site
var wci = new SP.WebCreationInformation();
wci.set_title('My New Web Site 2');
wci.set_description('Description Input');
wci.set_url('mynewwebsite7');
wci.set_language(1033);
wci.set_useSamePermissionsAsParentSite(true);
wci.set_webTemplate('STS#1');
// Create the new web in the client context
this.childWeb = this.web.get_webs().add(wci);
this.context.load(this.web);
this.context.load(this.childWeb);//, 'ServerRelativeUrl', 'Created');
// Now create it on the server
this.context.executeQueryAsync(Function.createDelegate(this, this.createSiteSucceeded),
Function.createDelegate(this, this.createSiteFailed));
this.web = context.get_web();
// Build out the WebCreationInformation for the new site
var wci = new SP.WebCreationInformation();
You can't write this in your code. You have to load the requestexecutor.js first and then make the client context or the rest API calls to get the desired result. also you have to give full control over site collection in the appmanifest.
How to get the Root Site collection url when the context is in a child site, in JavaScript or JQuery.
You could use the following using client object model
var clientContext = new SP.ClientContext();
var owebsite = clientContext.get_site.get_rootWeb();
Without client object model you can use the following
var siteCollectionPath= _spPageContextInfo.siteServerRelativeUrl;
var clientContext = new SP.ClientContext.get_current();
this.web = clientContext.get_site().get_rootWeb();
It's working for me.
Do you mean root web or root site collection?
This one will get you the root site collection:
_spPageContextInfo.siteAbsoluteUrl.replace(_spPageContextInfo.siteServerRelativeUrl, _spPageContextInfo.siteServerRelativeUrl == \"/\" ? \"/\": \"\") + \""
From my post: http://www.rdacorp.com/2015/03/alternate-solution-alternate-css-url-sharepoint-2013-online/
Below sample script shows how you can retrieve root web. The onQuerySucceedSample function alerts root site title.
getRootWeb = function () {
//Get and load a reference to the root web of the current site collection.
var ctx = new SP.ClientContext.get_current();
var site = ctx.get_site();
this.rootWeb = site.get_rootWeb();
ctx.load(this.rootWeb);
//Ask SharePoint to pull data for us
ctx.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceed),Function.createDelegate(this, this.onQueryFailed));
};
//Function executed on success
onQuerySucceed = function () {
alert(this.rootWeb.get_title());
};
//Function executed on failure
onQueryFailed = function (sender, args) {
alert('Unable to retrieve data from the SharePoint. Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
};
you can get the url without the client object model by using available information and string parse it down from there. Not as robust as the Client-Object model but significantly less complicated for simple tasks.
window.location.href
...gives you the full window url (e.g. "http://sitecollection.com/sites/mysite/Lists/myList/NewForm.aspx?ContentTypeId=0x01006AC2C39AA621424EBAD9C2AC8A54F8B9007B626ABEEB66E34196C46E13E0CA41A2&ContentTypeName=xxxx")
L_Menu_BaseUrl
Or
_spPageContextInfo.siteServerRelativeUrl
...(as Jinxed points out) will give you the relative url (e.g. "/sites/mysite")
I have a special requirement that I need to get all site collection URLs list from JQuery.Can any one please help on that
I am afraid that you cannot get the list of all site collections in pure JavaScript. I assume that you meant all existing site collections in a web application or in all web applications.
If your page (aspx) runs on the SharePoint server you can put some server-side code on the page "rendering" the list as JavaScript and then just access it. This would be the easiest way; probably using Page.ClientScript.RegisterStartupScript.
If your page (and/or the web application) runs outside the SharePoint farm you would have to create and deploy your web service (asmx) or a handler (ashx) to the SharePoint farm. You would probably respond with the site collection list as JSON content and consume it by jQuery on your page (AJAX).
The functionality is available in the server-side SharePoint API only. You would use SPWebService.ContentService.WebApplications and application.Sites to get the list in any case:
var json = new StringBuilder();
foreach (var site in SPWebService.ContentService.WebApplications.SelectMany(
application => application.Sites))
using (site) {
if (json.Length > 0)
json.Append(',');
json.Append('"').Append(site.Url).Append('"');
}
json.Insert(0, "[").Append("]");
--- Ferda
Try below code.you can get all site collection using client object model
function loadWebs() {
var clientContext = new SP.ClientContext.get_current();
this.webs = clientContext.get_web().get_webs();
clientContext.load(this.webs);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onWebsLoaded), Function.createDelegate(this, this.onQueryFailed));
}
function onQueryFailed(sender, args) {
alert('request failed ' + args.get_message() + '\n' + args.get_stackTrace());
}
function onWebsLoaded(sender, args) {
for (var i = 0; i < this.webs.get_count(); i++) {
alert(this.webs.itemAt(i).get_title());
}
}
ExecuteOrDelayUntilScriptLoaded(loadWebs, "sp.js");