【问题标题】:Sharepoint NewForm adding attachments programmaticallySharepoint NewForm 以编程方式添加附件
【发布时间】:2019-01-16 12:28:53
【问题描述】:

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

但是,当将文件添加到新项目的 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();

【问题讨论】:

    标签: sharepoint attachment


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      • 2014-01-04
      • 2011-06-10
      • 2013-06-08
      相关资源
      最近更新 更多