Attaching a file to an item using code

Posted: October 20, 2008 in Attachments, Object Model

If you are using a custom newform.aspx then you will face difficulties in adding attachments. There are two scenarios

  1. If you make your own infopath forms/user control then you will not be having the attachments option
  2. If you remove any columns(Default for that list) using sharepoint designer , you will have the option for attachments but it will not work.

In this case you have to go for coding.

To add an attachment to an item we will access the item which needs a file to be attached to it and we will use item.Attachments.Add() method to actually attach the file.

Add a .net FileUpload control and a button to your page and on the buttonclick event write the following code.

public void btnSubmit_Click(object sender, EventArgs e)
{
bool flag=false;
Microsoft.SharePoint.Administration.SPWebApplication webApp = this.web.Site.WebApplication;
webApp.FormDigestSettings.Enabled = false;
SPList list = web.Lists[“ACBS Client Request”];

//Upload the file on the server.
fileUpload.PostedFile.SaveAs(Request.PhysicalApplicationPath + “UploadedFiles\\” + fileUpload.FileName);


FileInfo file = new FileInfo(Request.PhysicalApplicationPath + “UploadedFiles\\” + fileUpload.FileName);

foreach (SPListItem attachItem in list.Items)
{
if (Convert.ToString(attachItem[“Request Number”]) == Convert.ToString(this.Request.QueryString[“reqno”]))
{
foreach (string fileName in attachItem.Attachments)
{
if (fileName == fileUpload.FileName)
{
flag = true;
}
}
if (flag == true)
{
lblSuccess.Text = “File with same name already exists”;
}
else
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
attachItem.Attachments.Add(file.Name, AddFile(file));
attachItem.Update();
});
lblSuccess.Text = “File Uploaded Successfully”;
}
break;
}
}
}

internal static byte[] AddFile(FileInfo file)
{
FileStream fStream = File.OpenRead(file.FullName);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
return contents;
}

Advertisements
Comments
  1. DustinH says:

    This is great… is there any way that you can do this in Javascript?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s