Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, November 28, 2011

Uploading a document to a document library using SharePoint Default WebServices

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.IO;
using System.Xml;
using MySite;
using System.Text;
public partial class Add_New_Document : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnUpload_Click(object sender, EventArgs e)
{



//Create a filestream containing the document you want to upload

FileStream oSourceFile = File.OpenRead(fuBrowse.PostedFile.FileName);

//Create a webrequest pointing to the site and document library you want to

//upload the document to. In addition specify the document name
string strOnlyFile = fuBrowse.PostedFile.FileName;

//onlyFile=onlyFile.Substring
strOnlyFile = strOnlyFile.Substring((fuBrowse.PostedFile.FileName).LastIndexOf(@"\") + 1);
string strCompleteFile="http://vlnrm:100/UserPages/"+strOnlyFile;
WebRequest oWr = WebRequest.Create(strCompleteFile);

oWr.Method = "PUT";

oWr.Headers.Add("Overwrite", "F");

//oWr.Timeout = Timeout.Infinite;

oWr.Credentials = CredentialCache.DefaultCredentials;



//Literally copy the bytes of the filestream into the request stream to "upload" the document to the library

byte[] oBytes = new byte[1024];

using (Stream oRq = oWr.GetRequestStream())

{

for (; ; )

{

int iBytes = oSourceFile.Read(oBytes, 0, oBytes.Length);

if (iBytes <= 0) break; oRq.Write(oBytes, 0, iBytes); } oSourceFile.Close(); } WebResponse oResponse = oWr.GetResponse(); //Now create the XML to submit to the list service web service StringBuilder oSb = new StringBuilder(); oSb.Append("");

oSb.Append(" ");

oSb.Append(" "+strCompleteFile+"");

//Change the title of the document - replace or add to the document properties as necessary

oSb.Append(" New Title");

oSb.Append("
");



XmlDocument oDoc = new System.Xml.XmlDocument();

XmlElement oXBatch = oDoc.CreateElement("Batch");

oXBatch.SetAttribute("OnError", "Continue");

oXBatch.SetAttribute("PreCalc", "TRUE");

oXBatch.SetAttribute("ListVersion", "0");

oXBatch.InnerXml = oSb.ToString();



//Do the update replace the ListWebService object with your web service object

MySite.Lists oLstSvc = new MySite.Lists();

oLstSvc.Credentials = CredentialCache.DefaultNetworkCredentials;

XmlNode oRet = oLstSvc.UpdateListItems("UserPages", oXBatch);
Page.RegisterClientScriptBlock("alert", "");

}
}

No comments:

Post a Comment