Pages

Wednesday, September 15, 2010

Create file upload webpart which creates folders and add files indocument library in Sharepoint

Hello Friends

Business Solutions:

In Project, we have requirement like there is one calculation Budget form and when it is viewed by Analyst, Manager etc. Every user can attach documents and drop comments about form.

Solution:

Here is the webpart for attaching documents and creating foders to sharepoint document library. The main thing I want to share here is how you can access particular folder on SharePoint site. How can you create Folder and get access files from particular folder and upload file on that folder for SharePoint site.

Let me discuss more information on that webpart:

Steps for this project:
  • Open Microsoft Visual Studio 2005/2008.
  • Add new Project.
  • Now go to CodebehindFile

  • For this webpart we need HtmlInputFile for htmlInputFile and FileStream for saving files on that folder. We add two namespaces
              using System.Web.UI.HtmlControls;
              using System.IO;
  • Now we have to create controls Like HtmlInputFile, CheckBox for Overwrite existing file or not, Two buttons for user input (what actions needed to do) Ok and Cancel.
  • Let’s create all Controls which are needed in webparts’s CreateChildControls.
          protected override void CreateChildControls()
          {
 base.CreateChildControls();
                btnOk = new Button();
                btnOk.Text = "OK";
                btnOk.Click += new EventHandler(btnOk_Click);
                btnOk.Width = 80;
 btnCancel = new Button();
 btnCancel.Text = "Cancel";
 btnCancel.Width = 80;
 btnCancel.Click += new EventHandler(btnCancel_Click);
 filePath = new HtmlInputFile();
 chkOverwrite = new CheckBox();
 chkOverwrite.Text = "Overwrite File If Exists!!!";
 this.Controls.Add(filePath);
 this.Controls.Add(chkOverwrite);
 this.Controls.Add(btnOk);
 this.Controls.Add(btnCancel);
     }

You can also specify all control’s custom properties over here according to  requirement.
Then we have to render controls now in this method specify how controls look like.

Difference between “CreateChildControls” and “RenderControl”:

In CretaeChildControls, it just creates controls and adds it to controlcollection.But Rendercontrols specifies that how and in which sequence controls should be displayed.So no matter in which sequence you create controls in CreateChildControls .
Everything depends on RenderControls that decides in which sequence it displays.


public override void RenderControl(HtmlTextWriter writer)
{
     try
    {
               this.filePath.RenderControl(writer);
               writer.Write(" ");
               this.chkOverwrite.RenderControl(writer);
               writer.Write("<br>");
               writer.Write("<br>");
               this.btnOk.RenderControl(writer);
               writer.Write("&nbsp;");
               this.btnCancel.RenderControl(writer);
           }

           catch (Exception excpt)
          {
                writer.Write(excpt.ToString());
          }       
   }

So now looking at two functions you can differentiate that in createchildcontrols we add btnOk first but in renderchildcontrols we specify before btncancel so it comes after OverwriteCheckbox and before CancelButton.We also specify tags like “<BR>,<HR> with their style, &nbsp;”from writer tag  to look good.

  • On button OK Click Add new file at our sharepoint site’s one of the folder.
Now first thing is that we have to take filename from filepath. Then we have to check whether folder where we    have to upload file is already available of not. If not we have to create that folder.

Then we have to check whether file is there and if yes then we have to overwrite or not by clicking on overwrite exists or not and if overwrite yes we have to delete already exiting file and add file otherwise we do not have to do anything.

void btnOk_Click(object sender, EventArgs e)
{
            SPContext.Current.Web.AllowUnsafeUpdates = true;
    string path = "";
            string[] fileName = filePath.PostedFile.FileName.Split('\\');
     int length = fileName.Length;
     // get the name of file from path
     string file = fileName[length - 1];
            SPFolderCollection folders = SPContext.Current.Web.Folders;
     SPFolder folder;

      if (SPContext.Current.Web.GetFolder("My Files").Exists)
     {
                folder = SPContext.Current.Web.GetFolder("My Files");
      }
      else
      {
                folder = folders.Add("My New Folder");
      }

      SPFileCollection files = folder.Files;
             Stream fStream = filePath.PostedFile.InputStream;
             byte[] MyData = new byte[fStream.Length];
             Stream.Read(MyData, 0, (int)fStream.Length);
             fStream.Close();
             bool bolFileAdd = true;
             for (int i = 0; i < files.Count; i++)
             {
                    SPFile tempFile = files[i];
                    if (tempFile.Name == file)
                   {
                          if (chkOverwrite.Checked)
                          {
                                 folder.Files.Delete(file);
                                 bolFileAdd = true;
                                 break;
                          }
                          else
                          {
                                  bolFileAdd = false;
                                  break;
                           }
             }
     }
     if (bolFileAdd)
     {
           SPFile fff = files.Add(file, MyData);
           SPContext.Current.Web.AllowUnsafeUpdates = false;
      }
    }
  • On Cancel button go back to Or Redirect to previous page.
          void btnCancel_Click(object sender, EventArgs e)
            {
                        Page.Response.Redirect(SPContext.Current.Site.Url);//URL OF PREVIOUS PAGE
            }
Now just Build&Deploy Project and do needed changes need for deploy webpart and add it to your page.

Disha Shah

8 comments:

  1. Error 1 An object reference is required for the nonstatic field, method, or property 'System.IO.Stream.Read(byte[], int, int)' C:\Documents and Settings\UALI\My Documents\Visual Studio 2005\Projects\FileUp\FileUp\FileUploadControl\FileUploadControl.cs 99 9 FileUp

    ReplyDelete
  2. Usman

    Only error description cannot give the entire picture of your error. Can you post some lines of code?

    From error description, I can only say that you need to create an instance of the class before calling the method.

    This kind of the error is caused by the fact that when you put them as class variables, they will need an instance of the class to be accessed.

    The Main method is static and doesn't belong to any particular instance and will therefore not be able to use non-static methods or variables.

    Hope this helps
    Disha Shah

    ReplyDelete
  3. Well explained but not detailed at all.
    Took me a lot of time to get that thing to work.
    You should have better mentioned which references one must include and what exactly to do. Not only show "some" snippetes.

    ReplyDelete
  4. Nice article..Basic example..With simple and short piece of code..Helped me..Thanks!!

    ReplyDelete
  5. @JoshGarfield:

    use Visual Studio to auto-add references.

    nice article Disha...thanks.

    ReplyDelete
  6. This comment has been removed by the author.

    ReplyDelete
  7. This comment has been removed by the author.

    ReplyDelete
  8. @Usman:
    Replace the line below in the code..

    Stream.Read(MyData, 0, (int)fStream.Length);

    with following..

    Stream stream = new MemoryStream();
    stream.Read(MyData, 0, (int)fStream.Length);

    ReplyDelete