使用 React 表单处理 Sharepoint 列表中的文件上传 [英] Handling file upload in Sharepoint List with React form

查看:50
本文介绍了使用 React 表单处理 Sharepoint 列表中的文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个带有 react 的表单 webpart,但我一直坚持上传文件,所以我想在点击提交按钮时上传文件,并且必须创建带有附件文件的共享点列表项.

上图仅供参考理解.

现在我可以在 sharepoint 列表中创建以上两个主题和评论,但不确定上传是否与 attachments 相同的列表项附加.

<ReactFileReader fileTypes={[".csv", ".xlsx", ".Docx", ".pdf"]} base64={true} handleFiles={this.handleFiles.bind(this)}><button className='btn' value={this.state.UploadedFilesArray.toString()} >Upload</button></ReactFileReader>

<div className={styles.row}><div ><button id="btn_add" className={styles.button} onClick={this.createItem.bind(this)}>提交</button>

上面的代码是上传和提交的,正如我所说的,我想在提交表单时附上附件.

 private createItem(): void {this.setState({status: '正在创建项目...',项目: []});const 主体:字符串 = JSON.stringify({'标题':this.state.subject,'评论':this.state.comments,});this.props.spHttpClient.post(`${this.props.siteUrl}/_api/Web/lists/getbytitle('${this.props.listName}')/items`,SPHttpClient.configurations.v1,{标题:{'接受':'应用程序/json;odata=nometadata',//"接受": "application/json; odata=verbose",'内容类型':'应用程序/json;odata=nometadata','odata 版本':''},身体:身体}).then((response: SPHttpClientResponse): Promise => {返回 response.json();控制台日志(响应)}).then((item: IListItem): void => {this.setState({状态:`项目'${item.Title}'(ID:${item.Id})成功创建`,项目: []});}, (error: any): void =>{this.setState({状态:'创建项目时出错:'+错误,项目: []});});}

上面的代码用于处理提交,现在任何人都可以帮助我创建句柄文件功能,当我点击提交按钮时,我想创建一个带有附件的共享点列表项的功能.还带有成功或错误消息.

解决方案

我建议你使用这个很棒的库 PNPJS 库,使用附件会很容易.

private handleFiles(f) {var filelist = f.fileList;var fileInfos: IAttachmentFileInfo[] = [];文件信息.push({name: "我的文件名 1",内容:字符串、blob 或数组";});//遍历文件for (var i = 0; i < filelist.length; i++) {//获取项目让文件:文件 = filelist.item(i);文件信息.push({名称:文件名,内容:文件});}this.setState({上传文件:fileInfos});}

private createItem(): void {sp.web.lists.getByTitle("mylist").items.add({'标题':this.state.subject}).then((r: IItemAddResult) => {r.item.attachmentFiles.addMultiple(this.state.uploadfiles);}).then(e => {console.log("创建成功");}).catch(e => {console.log("创建项目时出错" + e)});}

更多详情,请参考以下演示:SharedSPFx

I am creating a form webpart with react but I am stuck at uploading a file, So I want to upload a file when it hit submit button and that has to create sharepoint list item with attachment file.

above image is for reference to understand.

Now I am able to create Above two Subjects and comments in sharepoint list but unsure for upload to attach with same list item as attachments.

<div className={styles.row}>
          <ReactFileReader fileTypes={[".csv", ".xlsx", ".Docx", ".pdf"]} base64={true} handleFiles={this.handleFiles.bind(this)}>
            <button className='btn' value={this.state.UploadedFilesArray.toString()} >Upload</button>
          </ReactFileReader>
        </div>
        <div className={styles.row}>
        <div  >
          <button id="btn_add" className={styles.button} onClick={this.createItem.bind(this)}>Submit</button>
        </div>

The above code is for Upload and Submit, As I said I want to attach the attachment when I submit the form.

  private createItem(): void {  
    this.setState({  
      status: 'Creating item...',  
      items: []  
    });
    const body: string = JSON.stringify({
      'Title': this.state.subject,
      'Comments': this.state.comments,
    });    
    this.props.spHttpClient.post(`${this.props.siteUrl}/_api/Web/lists/getbytitle('${this.props.listName}')/items`,  
    SPHttpClient.configurations.v1,  
    {  
      headers: {  
        'Accept': 'application/json;odata=nometadata',  
        //"Accept": "application/json; odata=verbose",
        'Content-type': 'application/json;odata=nometadata',  
        'odata-version': ''  
      },
      body: body
    })  
    .then((response: SPHttpClientResponse): Promise<IListItem> => {  
      return response.json();  
      console.log(response)
    })  
    .then((item: IListItem): void => {  
      this.setState({
        status: `Item '${item.Title}' (ID: ${item.Id}) successfully created`,  
        items: []  
      });  
    }, (error: any): void => {  
      this.setState({  
        status: 'Error while creating the item: ' + error,  
        items: []  
      });  
    });  
  }

The above code is for handling the submit, Now can anyone help me creating the handle file function with the functionality that I want to create a sharepoint list item with an attachment when I hit the Submit button. Also with Success or Error message.

解决方案

I suggest you use this awesome library PNPJS library, it will be easy to work with attachments.

private handleFiles(f) {
 var filelist = f.fileList;

 var fileInfos: IAttachmentFileInfo[] = [];

 fileInfos.push({
   name: "My file name 1",
   content: "string, blob, or array"
 });

 // loop through files
 for (var i = 0; i < filelist.length; i++) {

   // get item
   let file: File = filelist.item(i);

   fileInfos.push({
     name: file.name,
     content: file
   });

 }

 this.setState({
   uploadfiles: fileInfos
 });
}

private createItem(): void {

  sp.web.lists.getByTitle("mylist").items.add({
    'Title': this.state.subject
  }).then((r: IItemAddResult) => {
    r.item.attachmentFiles.addMultiple(this.state.uploadfiles);
  }).then(e => {
    console.log("successfully created");
  }).catch(e => {
    console.log("Error while creating the item" + e)
  });
}

For more details, please refer to below demo: SharedSPFx

这篇关于使用 React 表单处理 Sharepoint 列表中的文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆