Adding a FileUpload component to #SharePoint webpart

Sometimes you need a regular submitting forms for your internet SharePoint site, which deals with customers or visitors to your site.

As a very simple module in your forms, you may need a FileUpload component to upload visitors files to a specific document library location, so here you are a simple peace of code to do so:
//trying uploading file to SharePoint Image Library
protected void UploadFile()
// this is a must be added so as to  supply a delegate that runs a subset of code in the.. //context of an account with higher privileges than the current user.


//fuImageUpload is our fileupload component
if (fuImageUpload.PostedFile != null)

//this checks that the component contains file

if(fuImageUpload.PostedFile.ContentLength > 0)
//converting the file to an array of bytes and read it by input stream

System.IO.Stream strm = fuImageUpload.PostedFile.InputStream;

byte[] byt = new byte[Convert.ToInt32 (fuImageUpload.PostedFile.ContentLength)];

strm.Read(byt, 0, Convert.ToInt32(fuImageUpload.PostedFile.ContentLength));

// Open site where document library is created.
using (SPSite objSite = new SPSite(“your SharePoint site”))
using (SPWeb objWeb = objSite.OpenWeb())
SPFolder mylibrary = objWeb.Folders[“the name of your document library”];

// Set AllowUnsafeUpdates = true to avoid security error

objWeb.AllowUnsafeUpdates = true;

mylibrary.Files.Add(System.IO.Path.GetFileName(fuImageUpload.PostedFile.FileName), byt);



you can use this method inside your webpart to upload any kind of files, enjoy.


About Hossam Kamal

Hossam Kamal Senior SharePoint Developer with high development skills in C#, ASP.NET, SharePoint Server Technologies, jQuery, CSS, XML, O.O.D, SSRS and MS.SQL Server.
This entry was posted in SharePoint General. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s