views:

484

answers:

1

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();
A: 

Try using SPAttachmentCollection.AddNow(string, byte[]) instead of SPAttachmentCollection.Add(string, byte[]). Using AddNow also means you won't have to call SPListItem.Update(). AddNow will call an update on its own, without causing errors as far as I've seen. Aside from that change, I have a method that runs almost exactly as your supplied code, so it should work that way.

ccomet