【问题标题】:React SPFx - Adding files to SharePoint list field using PnPjsReact SPFx - 使用 PnPjs 将文件添加到 SharePoint 列表字段
【发布时间】:2020-09-23 21:47:58
【问题描述】:

我正在使用带有 React 的 SPFx Webpart 构建一个应用程序。在我的一个组件上,我有一个用户可以填写的表格。我正在使用 PnPjs 将用户的响应推送到我的列表字段中。一切正常。

我正在研究如何将文件或附件字段类型添加到列表中。我看到我可以在 powerapps 中做到这一点。所以现在在我的“产品”列表中,我有一个名为attachments 的字段。当我从 SharePoint 的后端将文件附加到该字段,然后使用 PnPjs 调用列表时,附件字段不会返回有关文件的信息。而是 boolean 的真假。

pnp.sp.web.lists.getByTitle("Products").items.filter("Id eq '" + this.props.match.params.id + "'").top(1).get().then((items: any[]) => {
    console.log(items); 
}

所以这很完美,并返回了应该具有以下代码附件的项目。现在在我的items 控制台中,我返回Attachments: trueAttachments: false

我使用react-dropzone 允许用户上传文件。使用PnPjs 如何将文件上传到该项目?

这是我创建项目的方式:

pnp.sp.web.lists.getByTitle("Requests").items.add({
    Title: this.state.SuggestedVendor,
    Client_x0020_Email: this.state.getEmail,
    Created: this.state.startDate,
    Attachments: //need help here
}

这是我的下拉文件代码:

onDrop = (acceptedFiles) => {
   console.log(acceptedFiles);
   //Assuming this is where I do the logic
}

<Dropzone 
    onDrop={this.onDrop}
    multiple
    >
    {({getRootProps, getInputProps, isDragActive}) => (
        <div {...getRootProps()}>
        <input {...getInputProps()} />
        {isDragActive ? "Drop it like it's hot!" : 'Click me or drag a file to upload!'}
        </div>
    )}
</Dropzone>

这是我从console.log(acceptedFiles); 得到的回复:

[File]
0: File {path: "John-Hancock-signature.png", name: "John-Hancock-signature.png", lastModified: 1590783703732, lastModifiedDate: Fri May 29 2020 13:21:43 GMT-0700 (Pacific Daylight Time), webkitRelativePath: "", …}
length: 1

我在这里找到了有关如何推送文件的文档:https://pnp.github.io/pnpjs/sp/files/

【问题讨论】:

    标签: javascript reactjs typescript web-applications spfx


    【解决方案1】:

    您必须创建项目,然后为其添加附件。

    您可以使用 add 方法将附件添加到列表项。此方法采用字符串、Blob 或 ArrayBuffer。 pnp documentation

    onDrop = (acceptedFiles) => {
        acceptedFiles.forEach(file => {
    
            const reader = new FileReader()
    
            reader.onabort = () => console.log('file reading was aborted')
            reader.onerror = () => console.log('file reading has failed')
            reader.onload = async () => {
                // get file content
                const binaryStr = reader.result
    
                // assume we have itemId
                let itemId = 1;
                let request = await sp.web.lists.getByTitle("Requests").items.getById(itemId)();
                await request.attachmentFiles.add("file2.txt", "Here is my content");
            }
            reader.readAsArrayBuffer(file)
        })
    
    
    
    }
    
    
    

    【讨论】:

      猜你喜欢
      • 2020-06-25
      • 2021-06-10
      • 2010-10-22
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      • 2020-07-31
      • 1970-01-01
      • 2021-08-27
      相关资源
      最近更新 更多