如何在React中使用MS Graph API为自定义Teams应用实现文件上传
实现步骤
1. 前置准备
- 首先在你的Teams应用清单中配置Microsoft Graph所需的委托权限:
Files.ReadWrite.All、Group.ReadWrite.All,确保权限经过管理员同意 - 你需要通过Teams SSO获取访问Graph API的令牌,调用
microsoftTeams.authentication.getAuthToken()方法即可获取有效令牌,无需自行实现鉴权逻辑
2. 代码修改
首先更新组件的state,新增文件选择、上传状态相关的字段,新增文件选择和上传的处理方法,完整修改后代码如下:
import React from 'react'; import './App.css'; import * as microsoftTeams from "@microsoft/teams-js"; class Tab extends React.Component { constructor(props){ super(props) this.state = { context: {}, selectedFile: null, uploadStatus: '' } } componentDidMount() { new Promise((resolve) => { microsoftTeams.getContext(resolve); }) .then((context) => { this.setState({ context }); const queryParameters = new URLSearchParams({ function: "getDocuments", input: '"'+ context.userPrincipalName + '"',}); console.log(`userPrincipalName is '${context.userPrincipalName}'`); console.log(`teamName is '${context.teamName}'`); console.log(`http://localhost/openims/json.php?${queryParameters}`); return fetch(`http://localhost/openims/json.php?${queryParameters}`); }) .then((res) => res.json()) .then((result) => this.setState({ ...result })) .catch((error) => this.setState({ error })) .finally(() => this.setState({ isLoaded: true })); } // 处理文件选择 handleFileChange = (e) => { this.setState({ selectedFile: e.target.files[0], uploadStatus: '' }) } // 处理上传逻辑 handleUpload = async () => { const { selectedFile, context } = this.state; if (!selectedFile) { this.setState({ uploadStatus: '请先选择文件' }); return; } try { // 获取Graph访问令牌 const accessToken = await new Promise((resolve, reject) => { microsoftTeams.authentication.getAuthToken({ successCallback: resolve, failureCallback: reject }) }); // 上传到当前团队关联的OneDrive根目录下的指定文件夹,可自行修改路径 const uploadUrl = `https://graph.microsoft.com/v1.0/groups/${context.teamId}/drive/root:/上传文件夹/${selectedFile.name}:/content`; const response = await fetch(uploadUrl, { method: 'PUT', headers: { 'Authorization': `Bearer ${accessToken}`, 'Content-Type': selectedFile.type }, body: selectedFile }); if (response.ok) { this.setState({ uploadStatus: '文件上传成功' }); } else { const err = await response.json(); throw new Error(err.error.message); } } catch (error) { this.setState({ uploadStatus: `上传失败:${error.message}` }); } } render() { const { error, isLoaded, name, age, city, uploadStatus } = this.state; if (error) { return <div>Error: {error.message}</div>; } else if (!isLoaded) { return <div>Loading...</div>; } else { return ( <div> <ul> <li> {name} {age} {city} </li> </ul> {/* 新增文件上传区域 */} <div style={{marginTop: '20px'}}> <input type="file" onChange={this.handleFileChange} /> <button onClick={this.handleUpload} style={{marginLeft: '10px'}}>上传到团队OneDrive</button> {uploadStatus && <p style={{marginTop: '10px'}}>{uploadStatus}</p>} </div> </div> ); } } } export default Tab;
3. 补充说明
- 上述代码适用于小于4MB的文件上传,如果需要上传大于4MB的文件,需要使用Graph API的分片上传接口
- 如果需要上传到个人OneDrive而非团队OneDrive,将请求URL中的
/groups/${context.teamId}替换为/me即可 - 你可以自行修改URL中的路径部分,自定义文件存储的文件夹位置
内容的提问来源于stack exchange,提问作者7BitAscii
相关产品推荐
相关产品推荐

