如何使用PnPJS正确上传多附件至SharePoint并实现查看?
一、PnPJS attachmentFiles.add方法参数解释
在PnPJS的await item.attachmentFiles.add("file2.txt", "Here is my content");示例中,第二个参数**"Here is my content"是要上传的文件的实际内容**:
- 对于文本类文件(如
.txt),可以直接传入字符串; - 对于二进制文件(如图片、Excel、Word等),需要传入
ArrayBuffer或Blob类型的文件原始内容。
你之前的代码传入固定字符串'File added',所以上传后的文件内容就是这段文本,而非用户选择的文件实际内容。
二、React/TypeScript下多附件上传正确代码示例
以下代码实现支持指定格式的多文件上传,读取文件实际内容并上传到SharePoint列表项,新增附件不会覆盖已有内容:
1. 核心上传函数
import { sp } from "@pnp/sp"; import "@pnp/sp/items"; import "@pnp/sp/attachments"; // 允许的文件格式白名单 const ALLOWED_EXTENSIONS = [".xlsx", ".xls", ".doc", ".docx", ".ppt", ".pptx", ".txt", ".pdf", ".png", ".jpg", ".jpeg", ".gif", ".msg"]; // 上传多附件到指定列表项 const uploadMultipleAttachments = async (listId: string, itemId: number, files: FileList | null) => { if (!files) return; // 遍历所有选中文件 for (let i = 0; i < files.length; i++) { const file = files[i]; const fileExtension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase(); // 格式校验 if (!ALLOWED_EXTENSIONS.includes(fileExtension)) { console.error(`文件 ${file.name} 格式不允许,仅支持${ALLOWED_EXTENSIONS.join(', ')}`); continue; } // 读取文件原始内容(兼容所有文件类型) const fileContent = await file.arrayBuffer(); try { // 新增附件(不会覆盖已有附件) await sp.web.lists.getById(listId).items.getById(itemId).attachmentFiles.add(file.name, fileContent); console.log(`文件 ${file.name} 上传成功`); } catch (error) { console.error(`文件 ${file.name} 上传失败:`, error); } } };
2. React组件中调用示例
import React from "react"; const AttachmentUploader = () => { const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => { // 替换为你的SharePoint列表ID和目标项ID const targetListId = "your-list-guid-or-title"; const targetItemId = 123; await uploadMultipleAttachments(targetListId, targetItemId, e.target.files); }; return ( <div> <input type="file" multiple onChange={handleFileSelect} accept={ALLOWED_EXTENSIONS.join(',')} /> </div> ); }; export default AttachmentUploader;
三、无覆盖获取列表项所有附件代码示例
以下代码用于获取指定列表项的全部附件信息(包含可直接访问的下载链接):
const getItemAllAttachments = async (listId: string, itemId: number) => { try { const attachments = await sp.web.lists.getById(listId).items.getById(itemId).attachmentFiles.get(); // 格式化附件数据 return attachments.map(att => ({ fileName: att.FileName, downloadUrl: att.ServerRelativeUrl, fileSize: att.FileSize })); } catch (error) { console.error("获取附件失败:", error); return []; } }; // 使用示例 // const attachments = await getItemAllAttachments("your-list-id", 123);
内容的提问来源于stack exchange,提问作者some_new_dev_dude
相关产品推荐
相关产品推荐

