上传后仅获Item ID时,如何更新SharePoint文件标题?
方案一:上传时直接保留Library ID并获取Item ID(更高效)
在你现有的uploadDocument方法中,已经通过getLibraryIdByLibraryName或createLibrary拿到了文档库对应的libraryId(也就是List ID),完全不需要事后额外查询。只需在文件上传完成后,获取该文件的Item ID,直接复用已有的libraryId调用更新标题接口即可。
修改uploadDocument方法如下:
public async uploadDocument( name: string, content: any, contentLength: number, folderName: string, originalName: string ): Promise<{ itemId: string; libraryId: string }> { // 调整返回类型,返回Item ID和Library ID try { let libraryId = await this.getLibraryIdByLibraryName(folderName); if (!libraryId) { libraryId = await this.createLibrary(folderName); } const client = await this.getClient(); const fileExtension = originalName.slice(originalName.lastIndexOf('.')); const fileName = `${name}${fileExtension}`; const uploadSession = await client .api(`/sites/${this.siteId}/lists/${libraryId}/drive/root:/${fileName}:/createUploadSession`) .post({ item: { '@microsoft.graph.conflictBehavior': 'rename' } }); const { uploadUrl } = uploadSession; await axios.put(uploadUrl, content, { headers: { 'Content-Length': contentLength, 'Content-Range': `bytes 0-${contentLength - 1}/${contentLength}`, 'Content-Type': 'text/plain' } }); // 上传完成后获取文件对应的Item ID const fileItem = await client .api(`/sites/${this.siteId}/lists/${libraryId}/drive/root:/${fileName}:/`) .select('listItemId') .get(); return { itemId: fileItem.listItemId, libraryId }; } catch (error) { throw new DocumentStorageException('Cannot upload document to SharePoint'); } }
调用示例:
const { itemId, libraryId } = await uploadDocument(/* 传入你的参数 */); await updateDocumentTitle(libraryId, itemId, '你的新文档标题');
方案二:通过Item ID反向查询List ID
如果确实只有Item ID,需要获取对应的List ID,可以调用Microsoft Graph API查询Item的父引用信息,从中提取List ID。
新增一个获取List ID的方法:
private async getListIdByItemId(itemId: string): Promise<string> { const client = await this.getClient(); const item = await client .api(`/sites/${this.siteId}/items/${itemId}`) .select('parentReference') .get(); return item.parentReference.listId; }
调用更新标题接口时:
const targetItemId = '你的Item ID'; const listId = await getListIdByItemId(targetItemId); await updateDocumentTitle(listId, targetItemId, '你的新文档标题');
补充说明
- 优先选择方案一,避免额外的API请求,提升性能;
- 确保应用拥有
Sites.ReadWrite.All或对应文档库的读写权限,否则API调用会返回权限错误。
内容的提问来源于stack exchange,提问作者Manikant Jha
相关产品推荐
相关产品推荐

