SPFx 上传附件并将其添加到列表

SPFx uploading and adding attachment to a list

我在使用 PNP/SP 包上传和附加到共享点中的列表项时遇到了一些困难。我对输入文件组件没有太多经验,所以我想我可能缺少文件上传 html 元素和将文件提交到 SharePoint Web 服务之间的步骤。

到目前为止,我已经尝试对 PNP 示例进行一些更改 https://pnp.github.io/pnpjs/sp/docs/attachments/ 并尝试了一些不同的参数,但它们都倾向于导致 409 或 500 错误,一个错误提到它正在尝试GET 请求而不是 post.

我的代码在下面,当我明天进入办公室时,我会 post 完整的错误消息,但我们将不胜感激任何帮助。

private setButtonsEventHandlers(): void {   
let fileUpload = document.getElementById("fileUploadInput") 
if(fileUpload) {
  fileUpload.addEventListener('change', () => { 
    this.uploadFiles(fileUpload); 
  });
}
  }

private async uploadFiles(fileUpload) {
  let file = fileUpload.files[0];
  let attachmentsArray = this.state.attachmentsToUpload;


  let _web = new Web(this.props.wpContext.pageContext.site.absoluteUrl);
  let _listItem;
  let listUrlSplit: string[] = this.props.listUrl.split("/");
let listName: string = listUrlSplit[listUrlSplit.length-1];
  _listItem = await     _web.lists.getByTitle(listName).items.getById(this.props.id);

  let attachmentUpload = await _listItem.attachmentFiles.add(file.name,file)
}

我通过用字符串替换文件上传来测试代码(如下),它确实有效,所以我认为我的错误是误解了输入文件元素

let attachmentUpload = await _listItem.attachmentFiles.add("Testfile.txt","This is test content")

在此先感谢大家,享受周日剩下的一切;)

安迪

这是我的简单测试演示(React 框架)。

组件.tsx

<div className={ styles.column }>
              <input type='file' id='fileUploadInput' name='myfile'/>
              <span className={ styles.title }>Welcome to SharePoint!</span>
              <p className={ styles.subTitle }>Customize SharePoint experiences using Web Parts.</p>
              <p className={ styles.description }>{escape(this.props.description)}</p>
              <a href="https://aka.ms/spfx" className={ styles.button }>
                <span className={ styles.label }>Learn more</span>
              </a>
            </div>

webpart.ts

public render(): void {
    const element: React.ReactElement<IPnpspUploadAttachementProps > = React.createElement(
      PnpspUploadAttachement,
      {
        description: this.properties.description
      }
    );

    ReactDom.render(element, this.domElement);
    this.setButtonsEventHandlers();
  }

  private setButtonsEventHandlers(): void {   
    let fileUpload = document.getElementById("fileUploadInput") 
    if(fileUpload) {
      fileUpload.addEventListener('change', () => { 
        this.uploadFiles(fileUpload); 
      });
    }
    }

    private async uploadFiles(fileUpload) {
      let file = fileUpload.files[0];
      //let attachmentsArray = this.state.attachmentsToUpload;        
      let item = sp.web.lists.getByTitle("MyList").items.getById(15);
      item.attachmentFiles.add(file.name,file).then(v => {
          console.log(v);
      });
      //let attachmentUpload = await _listItem.attachmentFiles.add(file.name,file)
    }