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;
you can use this method inside your webpart to upload any kind of files, enjoy.