Programmatically uploading an attachment to a list item in WSS3/MOSS 2007

If you need to upload a file into a SharePoint document library through code you can get started with this MSDN article: How to: Upload a File to a SharePoint Site from a Local Folder.

In case you need to do the upload the file as an attachment to a custom list using the object model, the approach is slightly different. Adding a file to the list item can be done by accessing the Attachments collection of the SPListIem:

//code snippet
SPList list = web.Lists[
new Guid("my list id")];
if (list != null
)
{
  web.AllowUnsafeUpdates =
true
;
  SPListItem item = list.Items.Add();
  item["Title"] = "my title";

 if (fileAttachment.PostedFile != null && fileAttachment.HasFile)
  {
    
Stream
fStream = fileAttachment.PostedFile.InputStream;

     byte[] contents = new byte[fStream.Length];
     fStream.Read(contents, 0, (
int
)fStream.Length);
     fStream.Close();
     fStream.Dispose();

     SPAttachmentCollection attachments = item.Attachments;
    
string fileName = Path.GetFileName(fileAttachment.PostedFile.FileName);
    
attachments.Add(fileName, contents);

   }

  item.Update();
  web.AllowUnsafeUpdates =
false;

}

//snippet end

 

Feedback

Posted on 24 July 2007 @ 18:03

I have tried several different methods to upload a file and update the associated items for the file and I always get the following error:
To add an item to a document library, use SPFileCollection.Add()

My code is as follows:

if (htmlFileUpload.PostedFile != null)
{
int found;
string libraryName = "Employee Availability Resumes";
string fileExt = "";
string destUrl = strDocLibUrl;
string uploadedFile = htmlFileUpload.PostedFile.FileName;
found = uploadedFile.IndexOf(".");
fileExt = uploadedFile.Substring(found).Trim();
using (SPWeb web = new SPSite(destUrl).OpenWeb())
{
try
{
SPList list = web.Lists[libraryName];
if (list != null)
{
web.AllowUnsafeUpdates = true;
SPListItem item = list.Items.Add();
item["Employee Number"] = txtEmpNo.Text;
item["Tracking ID"] = strTrackingId;

if (htmlFileUpload.PostedFile != null)
{
Stream fStream = htmlFileUpload.PostedFile.InputStream;
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
fStream.Dispose();
string fileName = Path.GetFileName(htmlFileUpload.PostedFile.FileName);
SPFile newFile = list.RootFolder.Files.Add(fileName, contents, true);
}
item.Update();
web.AllowUnsafeUpdates = false;
}
return true;
}

Any help on this would be greatly appreciated.
Thanks,
Brian

Posted on 25 July 2007 @ 21:09

Hi Brian,
I think you should first upload the file to the library and then update its properties. Adding a new list item first will probably not work.

Based on your code I've slightly adapted it to what I think should work (without having actually tried out the code so no promises here):

if (htmlFileUpload.PostedFile != null)
{
int found;
string libraryName = "Employee Availability Resumes";
string fileExt = "";
string destUrl = strDocLibUrl;
string uploadedFile = htmlFileUpload.PostedFile.FileName;
found = uploadedFile.IndexOf(".");
fileExt = uploadedFile.Substring(found).Trim();
using (SPWeb web = new SPSite(destUrl).OpenWeb())
{
try
{
SPList list = web.Lists[libraryName];
if (list != null)
{
web.AllowUnsafeUpdates = true;

Stream fStream = htmlFileUpload.PostedFile.InputStream;
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
fStream.Dispose();
string fileName = Path.GetFileName(htmlFileUpload.PostedFile.FileName);
SPFile newFile = list.RootFolder.Files.Add(fileName, contents, true);

Hashtable fileProps = file.Properties;
fileProps["Employee Number"] = txtEmpNo.Text;
fileProps["Tracking ID"] = strTrackingId;
file.Update();

web.AllowUnsafeUpdates = false;
}
return true;
}
catch (System.Exception exc)
{
//error handling}
}

}
}

Posted on 26 July 2007 @ 19:50

Katrien,

It worked like a charm (after I changed file.Properties and file.Update to newFile.Properties and newFile.Update).

This one had me stumped for several days so thank you very much!!

Brian

Posted on 26 July 2007 @ 20:51

Glad it worked Brian,
As I said, I changed the code without actually compiling or testing it ;-)

Posted on 09 October 2007 @ 11:22

Thx man! :D

Posted on 26 March 2008 @ 15:46

Thanks this was very handy. Worked straight off.

Posted on 06 May 2008 @ 22:55

Thanks man... your code works perfectly!

Posted on 31 July 2008 @ 15:02

Hi,

I am using the SPFile.Update() method as above to alter some meta data properties of a file in a sharepoint list. This works fine except I cannot update the Name or Title of the document just the other properties I have created.

fileProperties["Name"] = newNameString;
file.Update();

I am trying to upload multiple versions of the same file keeping the version history however the file name may have changed between versions but I am unable to change a file name for an existing document! I have tried various options but no joy!

Any ideas?

Thanks,

Tim

Posted on 18 June 2009 @ 14:48

Well, this post certainly is old, but just in case anyone googles this:

The metadata is not updated via the update method of the SPFile object as this is a representation of the actual file while the metadata is attached to the list item representation of the file.
To update the metdata you have change the data of the item and then update the list item, not the file itself:

file.Item["somedescriptor"] = somevalue;
file.Item.Update();

Posted on 06 August 2009 @ 05:37

Great Post!! It helped me Uploading a document to the document library & updating columns also.

Posted on 22 January 2010 @ 21:56

Hello Katrien,

Uploading the attachment file is worked fine for me. Thanks for providing this but now I'm facing the problem with showing the attachment image in grid with specific size is not getting to me. Can you tell me how to control the attached image width and height size in sharepoint webpart.

Thanks in advance,
Madan

Please post your comments:

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Copyright © 2007 Katrien De Graeve.