我正在使用SPFX创建一个SP Web部件。 该webpart必须能够使用一个按钮或多个按钮(每个文件一个)来上传多个文件。
我正在尝试使用此功能: https://pnp.github.io/pnpjs/sp/attachments/#add-multiple
但是它没有显示如何在React状态下使用它。您会看到,我希望能够将文件上传状态保存,因此可以使用按钮将其提交。那是当它附加到SP中的列表项时。 然后,我希望Webpart在用户单击该项目时能够显示其附件。这就是为什么我需要使用状态。
我已阅读以下内容: React SPFx - Adding files to SharePoint list field using PnPjs
和: Handling file upload in Sharepoint List with React form
但是他们不清楚。
有人可以提供一个示例,说明如何使用带有状态的React组件类使用pnpjs附件吗?
答案 0 :(得分:1)
我的测试代码供您参考:
import * as React from 'react';
import styles from './NewReactSpfx.module.scss';
import { INewReactSpfxProps } from './INewReactSpfxProps';
import { escape } from '@microsoft/sp-lodash-subset';
import { Web } from "sp-pnp-js";
import IAttachmentInfo from "sp-pnp-js";
export default class NewReactSpfx extends React.Component<INewReactSpfxProps, any> {
public constructor(props) {
super(props);
this.state = {
fileInfos: null
};
}
public render(): React.ReactElement<INewReactSpfxProps> {
return (
<div className={styles.newReactSpfx}>
<div className={styles.container}>
<div className={styles.row}>
<div className={styles.column}>
<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>
<input type="file" multiple={true} id="file" onChange={this.addFile.bind(this)} />
<input type="button" value="submit" onClick={this.upload.bind(this)} />
</div>
</div>
</div>
);
}
private addFile(event) {
//let resultFile = document.getElementById('file');
let resultFile = event.target.files;
console.log(resultFile);
let fileInfos = [];
for (var i = 0; i < resultFile.length; i++) {
var fileName = resultFile[i].name;
console.log(fileName);
var file = resultFile[i];
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
//Push the converted file into array
fileInfos.push({
"name": file.name,
"content": e.target.result
});
}
})(file);
reader.readAsArrayBuffer(file);
}
this.setState({fileInfos});
console.log(fileInfos)
}
private upload() {
let {fileInfos}=this.state;
console.log(this.props)
let web = new Web(this.props.context.pageContext.web.absoluteUrl);
web.lists.getByTitle("testn").items.getById(2).attachmentFiles.addMultiple(fileInfos);
}
}
您可以在此处获得完整的项目:
https://github.com/Amos-IT/SharePoint-FrameWork-Demos/tree/master/NewReactSPFX
已更新:
private _onSubmit = (ev) => {
this.setState({
FormStatus: 'Submitted',
}, () => {
sp.web.lists.getByTitle("PanelMeetings").items.add({
Title: this.state.Title,
StartDate: this.state.PanelStartDate,
}).then(r=>{
r.item.attachmentFiles.add(this.state.fileInfos)
});
});