Sharepoint NewForm adding attachments programatically

Posted by CodeSpeaker on Stack Overflow See other posts from Stack Overflow or by CodeSpeaker
Published on 2010-04-01T08:04:43Z Indexed on 2010/05/12 19:04 UTC
Read the original article Hit count: 310

Filed under:
|

I have a list with a custom form which contains a custom file upload control. As soon as the user selects a file and clicks upload, i want this file to go directly to the attachments list within that listitem.

However, when adding the file to SPContext.Current.ListItem.Attachments on a new item, the attachment wont show up in the list after saving.

If i instead use item.Update() on the new item after adding the attachment i get an error in Sharepoint, but when i then go back to the list, the item is there with its attachment. It seems like its trying to create 2 new entries at once when i save (item.Update) which results in the second of those crashing.

What would be the correct way to add attachments this way?

oSPWeb.AllowUnsafeUpdates = true;

// Get the List item
SPListItem listItem = SPContext.Current.ListItem;

// Get the Attachment collection
SPAttachmentCollection attachmentCollection = listItem.Attachments;

Stream attachmentStream;
Byte[] attachmentContent;

// Get the file from the file upload control
if (fileUpload.HasFile)
{
    attachmentStream = fileUpload.PostedFile.InputStream;

    attachmentContent = new Byte[attachmentStream.Length];

    attachmentStream.Read(attachmentContent, 0, (int)attachmentStream.Length);

    attachmentStream.Close();
    attachmentStream.Dispose();

    // Add the file to the attachment collection
    attachmentCollection.Add(fileUpload.FileName, attachmentContent);
}

// Update th list item
listItem.Update();

© Stack Overflow or respective owner

Related posts about sharepoint

Related posts about attachments