Sharepoint List Attachments in a Webpart : The Solution
It's not a headache until you can do without it, but to use the sharepoint's attachment controls can be a pain in you know what. Try the solution below and save your self from same.
~Adding attachment Functionality in a Web Part.
//Create Controls
protected override void CreateChildControls()
~Adding attachment Functionality in a Web Part.
//Attachment Controls
//Add the Attachment Controls in the webpart, the attachment upload is the
//control to upload and AttachmentsField displays the list of all attachments
AttachmentButton btnAttach;
AttachmentUpload uploadAttach;
AttachmentsField fieldAttach;
HiddenField hDeleteAttachs;
protected override void RenderWebPart(HtmlTextWriter output)
{
//Add the javascript which will handle the list of attachments that have been //marked as deleted and add them to the Hidden Fiels, Actually its adds the //GUID of the Attachment(the delete attachment function use that)
output.Write("'<'script'>'");
output.Write("'<'script'>'");
output.Write("function RemoveAttachmentFromServer(guid, bRecycleBinEnabled){");
output.Write("var L_ConfirmDelete_TXT='Are you sure you want to delete this attachment?';");
output.Write("var L_ConfirmRecycle_TXT='Are you sure you want to send this attachment to the site Recycle Bin?';");
output.Write("var strWarning;document.getElementById('"+hDeleteAttachs.ClientID+"').value += guid + ';';");
output.Write("if (bRecycleBinEnabled){");
output.Write(" strWarning=L_ConfirmRecycle_TXT; } else { strWarning=L_ConfirmDelete_TXT; }");
output.Write("if (confirm(strWarning)) {");
output.Write("document.getElementById('idAttachmentsTable').deleteRow(document.getElementById(guid).rowIndex);");
output.Write("document.getElementsByName('attachmentsToBeRemovedFromServer').item(0).value+=guid+';';");
output.Write("if (document.getElementById('idAttachmentsTable').rows.length==0){");
output.Write("document.getElementById('idAttachmentsRow').style.display='none';} }} fuction gotoURL(sURL){window.location=sURL; return false;}");
output.Write("'<'/script'>'");
//Render all the controls
//Looks simple aah! But remember to include the attachment button in a span //with id “part1”
// Yes, that is required, otherwise keep expermenting…..
//The Attachment Upload control has to be in a control with ID = “idAttachmentRow”
//Replace '<' with <
//Replace '<' with <
//P.S. : This is one of the most important aspect
output.Write("’<’td’>’");
output.Write("’<’span id='part1'’>’");
btnAttach.RenderControl(output);
output.Write("’<’/span’>’");
output.Write("’<’/td’>’<’/tr’>’<’tr’>’<’td id='idAttachmentsRow'’>’");
uploadAttach.RenderControl(output);
output.Write("’<’/td’>’<’/tr’>’<’tr’>’<’td’>’");
fieldAttach.RenderControl(output);
output.Write("’<’/td’>’<’/tr’>’");
//Create Controls
protected override void CreateChildControls()
{
//Attachment Controls
btnAttach = new AttachmentButton();
btnAttach.ListId = list.ID;
btnAttach.ControlMode = SPControlMode.New;
btnAttach.Text = "Add Attachment";
this.Controls.Add(btnAttach);
fieldAttach = new AttachmentsField();
fieldAttach.ListId = list.ID;
fieldAttach.FieldName = "Attachments";
fieldAttach.ControlMode = SPControlMode.New;
this.Controls.Add(fieldAttach);
uploadAttach = new AttachmentUpload();
uploadAttach.ListId = list.ID;
uploadAttach.ControlMode = SPControlMode.New;
this.Controls.Add(uploadAttach);
//Hidden Field as mentioned above
hDeleteAttachs = new HiddenField();
hDeleteAttachs.ID = "hHiddenFields";
this.Controls.Add(hDeleteAttachs);
}
//Submit ,call attachment functions, First Add then delete
void btnSubmit_Click(object sender, EventArgs e)
{
//That's the way it is
AddAttachments(ref item);
item.Update();
DeleteAttachments(ref list, ref item);
}
//Delete the Attachments, Function
void DeleteAttachments(ref SPList list, ref SPListItem item)
{
try
{
#region Delete
SPFileCollection files = null;
SPFolder itemFolder = null;
//Get tha Attachment Folder
string strAttchmentFolderURL = item.Attachments.UrlPrefix +"/" + item.ID.ToString();
if (list.RootFolder.SubFolders.Count > 0)
{
if (list.RootFolder.SubFolders["Attachments"] != null)
{
itemFolder = list.RootFolder.SubFolders["Attachments"];
}
}
//Read the hidden field contaning the list of deleted attchments GUID
if (!hDeleteAttachs.Value.Equals(""))
{
string strValue = hDeleteAttachs.Value;
string[] strIDs = strValue.Split(';');
for (int i = 0; i < strID.Length; i++)
{
string strTempID = strIDs[i];
//I know there is better way to remove characters
strTempID = strTempID.Replace("{", "");
strTempID = strTempID.Replace("}", "");
//Get all the files in Attachment Folder that matches the GUID
#region getFiles
if (itemFolder.SubFolders[strAttchmentFolderURL] != null)
{
files = itemFolder.SubFolders[strAttchmentFolderURL].Files;
}
#endregion
foreach (SPFile file in files)
{
if (strTempID.ToLower().Equals(file.UniqueId.ToString().ToLower()))
{
//Delete the file finally
file.Delete();
break;
}
}
}
}
#endregion
}
catch
{
}
}
//Add attchments
void AddAttachments(ref SPListItem item)
{
try
{
for (int i = 0; i < (Page.Request.Files.Count - 1); i++)
{
try
{
//Get the list of files for attachments
HttpPostedFile newAttach = Page.Request.Files[i];
byte[] fileContents = new byte[newAttach.ContentLength - 1];
newAttach.InputStream.Seek(0, System.IO.SeekOrigin.Begin);
newAttach.InputStream.Read(fileContents, 0, newAttach.ContentLength - 1);
System.IO.FileInfo fInfo = new System.IO.FileInfo(newAttach.FileName);
item.Attachments.Add(fInfo.Name, fileContents);
}
catch { continue; }
}
}
catch {
}
}
That’s all folks !