2010-04-01 69 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將自行調用更新,而不會導致錯誤。除了這種改變之外,我有一個方法幾乎完全像你提供的代碼那樣運行,所以它應該以這種方式工作。

相關問題