Monday, March 10, 2014

Upload Documents to Document Library using file upload control in SharePoint

In Aspx page:-
------------------
<asp:FileUpload runat="server" ID="FileUpload1"></asp:FileUpload>

<asp:ImageButton runat="server" ID="imgbtnUpdateAttachment" OnClick="fileUpload_Click"
ImageUrl="../SiteAssets/Buttons/update_attachement.png"></asp:ImageButton>

In Aspx.cs Page:-
---------------------
protected void fileUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile && FileUpload1.PostedFile != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPSite site = SPContext.Current.Site;
                    SPWeb web = SPContext.Current.Web;

                    string DocumentLibName = "Test Temp Documents";

                    web.AllowUnsafeUpdates = true;
                    if (FileUpload1.PostedFile != null)
                    {
                        Stream fStream = FileUpload1.PostedFile.InputStream;
                        byte[] content = new byte[fStream.Length];
                        fStream.Read(content, 0, (int)fStream.Length);

                        string Filename = FileUpload1.FileName;
          string destUrl = SPContext.Current.Site.Url + DocumentLibName + "/" + Filename;
                        SPFile spfile = web.Files.Add(destUrl, content, true);
                        spfile.Item["DocID"] = "1234567";
                        spfile.Item.Update();
                        fStream.Flush();
                        fStream.Close();
                        fStream.Close();
                        fStream.Dispose();
                    }
                    else
                    {
                        throw new FileNotFoundException("File Not Found");
                    }
                    web.AllowUnsafeUpdates = false;

                });
            }
        }
-----------------------------------------------------------------
Thank You

No comments:

Post a Comment

Featured Post

Create SharePoint Folder Structure in Destination (Only If Not Exists)

Why This Script Is Safe You can run it multiple times It will not create duplicate folders It will only create missing folders S...

Popular posts