Sharepoint NewForm以编程方式添加附件

时间:2010-04-01 08:04:44

标签: sharepoint attachment

我有一个包含自定义文件上传控件的自定义表单列表。 一旦用户选择文件并单击上传,我希望此文件直接转到该列表项中的附件列表。

但是,在新项目上将文件添加到SPContext.Current.ListItem.Attachments时,附件在保存后不会显示在列表中。

如果我在添加附件后在新项目上使用item.Update(),我会在Sharepoint中收到错误,但是当我返回列表时,该项目就会附带其附件。 当我保存(item.Update)导致第二次崩溃时,它似乎试图一次创建2个新条目。

以这种方式添加附件的正确方法是什么?

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

1 个答案:

答案 0 :(得分:0)

尝试使用SPAttachmentCollection.AddNow(string, byte[])代替SPAttachmentCollection.Add(string, byte[])。使用AddNow还意味着您不必调用SPListItem.Update()。 AddNow将自己调用更新,而不会导致我看到的错误。除了这个改变,我有一个方法几乎完全按照你提供的代码运行,所以它应该这样工作。

相关问题