2010-04-01 116 views
0

我有一个包含自定义文件上传控件的自定义表单的列表。 只要用户选择一个文件并点击上传,我希望该文件直接进入该列表项中的附件列表。Sharepoint NewForm以编程方式添加附件

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

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

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

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

回答

0

尝试使用的SPAttachmentCollection.AddNow(string, byte[])代替SPAttachmentCollection.Add(string, byte[])。使用AddNow也意味着您不必拨打SPListItem.Update()。就我所见,AddNow将自行调用更新,而不会导致错误。除了这种改变之外,我有一个方法几乎完全像你提供的代码那样运行,所以它应该以这种方式工作。

相关问题