Thursday 21 November 2013

sharepoint custom attachement upload control with example

Share it Please
                        sharepoint custom attachement upload control with example 

Design Code:-

<table> <tr><td>
<asp:HiddenField Value="hDeleteAttachs" ID="hHiddenFields" runat="server" />
</td></tr>
<tr>
<td><span id="part1">
<SharePoint:AttachmentButton runat="server" ID="btnAttach" ControlMode="new" Text="Add Attachment">
</SharePoint:AttachmentButton> </span></td></tr>
<tr><td id='idAttachmentsRow'>
<SharePoint:AttachmentUpload runat="server" ID="uploadAttach" ControlMode="New">
</SharePoint:AttachmentUpload></td></tr>

<tr><td><SharePoint:AttachmentsField runat="server" ID="fieldAttach" ControlMode="new" FieldName="Attachments">
</SharePoint:AttachmentsField></td></tr>
</table>
<asp:Button ID="submitButton" runat="server" Text="Submit" OnClick="submitButton_Click" />
Cs Code:-

SPSite Objsite = null;
SPWeb Objweb = null;
SPSite noprevsite = null;
SPWeb noprevweb = null;
SPList Olist = null;
SPListItem Osplistitem = null;
protected void Page_Load(object sender, EventArgs e)
{
noprevsite = SPContext.Current.Site;
noprevweb = noprevsite.OpenWeb();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
Objsite = new SPSite(noprevsite.ID);
Objweb = Objsite.OpenWeb(noprevweb.ID);
Objweb.AllowUnsafeUpdates = true;
Olist = Objweb.Lists["Users"];
btnAttach.ListId = Olist.ID;
uploadAttach.ListId = Olist.ID;
fieldAttach.ListId = Olist.ID;
Osplistitem = Olist.Items.Add();
});
}
protected void submitButton_Click(object sender, EventArgs e)
{

SPWeb mySite = SPContext.Current.Web;
SPList myList = mySite.Lists["Users"];
SPListItem myListItem = myList.Items.Add();
myListItem["Title"] = "myTitle";
if (HttpContext.Current.Request.Files.Count > 0)
{
HttpFileCollection uploads = HttpContext.Current.Request.Files;
SPAttachmentCollection attachments;
for (int i = 0; i < uploads.Count; i++)
{
Stream fs = uploads[i].InputStream;
byte[] fileContents = new byte[fs.Length];
fs.Read(fileContents, 0, (int)fs.Length);
fs.Close();
attachments = myListItem.Attachments;
string fileName = Path.GetFileName(uploads[i].FileName);
attachments.Add(fileName, fileContents);
}
myListItem.Update();
}
}

2 comments:

  1. Hi,
    I got nothing when I click on Ok button. Can you advice me more on it. Thanks

    ReplyDelete
  2. Just add id="idAttachmentsTable" to table tag

    ReplyDelete

Followers

Follow The Author