Uploading multiple files on save button to SharePoint List Item
Attachment Related tasksFile Upload Event
**************************************************************************
public void UploadButton_onClick(object sender, EventArgs e))
{
DataTable fileDt =new DataTable ();
DataRow row=null;
fileDt = GetFileTable();
row = fileDt.NewRow();
row["Id"] =
attachmentId;
row["FileName"] = fileAttachmentUpload.FileName;
row["FilePath"] = "";
row["FileContent"] = GetFileStream(); // This is File Byte stream
fileDt.Rows.Add(row);
ViewState["FilesList"] = fileDt;
}Breaking the file in File Stream. and return the Byte array
************************ **************************************************
/// <summary>
/// Returning Files in byte [] array after reading by stream
/// </summary>
/// <returns></returns>
public byte[] GetFileStream()
{
byte[] contents = null;
try
{
Stream fStream = fileAttachmentUpload.PostedFile.InputStream;
contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
}
catch (Exception ex)
{
errorLog.LogEntery(ex);
}
return contents;
}
Attaching the files to SharePoint ListItem *************************************************************************
/// <summary>
/// Adding Attachment Files To SharePoint ListItem
/// </summary>
/// <param name="Item"></param>
public void AddAttachmentToList(SPListItem Item)
{
DataTable dt = null;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWeb web = SPContext.Current.Web;
if (ViewState["FilesList"] != null)
{
dt = (DataTable)ViewState["FilesList"];
foreach (DataRow row in dt.Rows)
{
byte[] fs = (byte[])row["FileContent"];
string fileName = (string)row["FileName"];
SPAttachmentCollection attachments = Item.Attachments;
attachments.Add(fileName, fs);
}
}
web.AllowUnsafeUpdates = true;
taskItem.Update();
web.AllowUnsafeUpdates = false;
});
}
catch (Exception ex)
{
errorLog.LogEntery(ex);
}
}
Getting All Attachment from ListItem
/// Getting all attachment from a listitem with fileName and its file url and return in Hashtable
public Hashtable GetListAttachemnts(SPListItem taskItem)
{
Hashtable _listItems = new Hashtable();
try
{
SPAttachmentCollection attachments = taskItem.Attachments;
foreach (var attachment in attachments)
{
string attachmentAbsoluteURL = taskItem.Attachments.UrlPrefix + attachment;
_listItems.Add(attachment, attachmentAbsoluteURL);
}
}
catch (Exception ex)
{
errorLog.LogEntery(ex);
}
return _listItems;
}
No comments:
Post a Comment