新手求助:如何向SharePoint上传数据及通过REST上传文件?
Hey there! Since you're new to SharePoint and looking to upload files via the REST API, let me break this down clearly for you, plus cover other common upload methods to give you flexible options.
First up, the REST API approach—perfect if you're building an automated or custom solution. Here's how to pull it off:
1. 获取有效的访问令牌
You'll need an OAuth 2.0 access token to authenticate your requests. For testing, you can use tools like Postman to generate one (make sure to request permissions like Files.ReadWrite.All or site-specific edit permissions). In code, libraries like MSAL (Microsoft Authentication Library) can handle token generation and renewal for you seamlessly.
2. 构造上传请求端点
Target the SharePoint REST endpoint for your target document library. For example, if uploading to the "Shared Documents" library:https://<your-sharepoint-site-url>/_api/web/GetFolderByServerRelativeUrl('/Shared%20Documents')/Files/add(overwrite=true,url='<your-filename>')
overwrite=true: Replaces the file if it already exists (set tofalseif you want to prevent overwriting)<your-filename>: The name you want the file to have in SharePoint
3. 设置请求头
Include these headers in your POST request:
Authorization: Bearer <your-access-token>: Authenticates your request with SharePointContent-Type: application/octet-stream: Tells SharePoint you're sending binary file dataAccept: application/json;odata=nometadata: Optional, simplifies the response format to avoid extra metadata
4. 发送带文件数据的请求
Send a POST request where the body is the binary content of your file. Here are quick examples for different tools:
Curl 示例
curl --location --request POST 'https://contoso.sharepoint.com/_api/web/GetFolderByServerRelativeUrl('/Shared%20Documents')/Files/add(overwrite=true,url='test-notes.txt')' \ --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \ --header 'Content-Type: application/octet-stream' \ --data-binary '@/home/user/Documents/test-notes.txt'
JavaScript (Fetch API) 示例
const uploadToSharePoint = async () => { const siteUrl = "https://contoso.sharepoint.com"; const folderPath = "/Shared%20Documents"; const fileName = "project-plan.pdf"; const accessToken = "YOUR_VALID_ACCESS_TOKEN"; const localFileUrl = "/local/path/to/project-plan.pdf"; // 将本地文件转为Blob格式 const fileResponse = await fetch(localFileUrl); const fileBlob = await fileResponse.blob(); // 发送上传请求 const uploadResponse = await fetch( `${siteUrl}/_api/web/GetFolderByServerRelativeUrl('${folderPath}')/Files/add(overwrite=true,url='${fileName}')`, { method: "POST", headers: { "Authorization": `Bearer ${accessToken}`, "Content-Type": "application/octet-stream" }, body: fileBlob } ); const result = await uploadResponse.json(); console.log("文件上传成功!", result); }; uploadToSharePoint();
If REST isn't the right fit for your use case, here are other reliable, beginner-friendly options:
Microsoft Graph API: A unified API for all Microsoft 365 services. The upload endpoint looks like
POST /sites/{site-id}/drive/items/{folder-id}:/{filename}:/content. It works similarly to SharePoint REST but is better if you're integrating with other Office 365 tools (like Outlook or Teams).PowerShell (SharePoint Online Management Shell): Perfect for scripted uploads without writing complex code. Install the module, connect to your site, and upload with two simple commands:
# 连接到SharePoint站点(会弹出登录窗口) Connect-PnPOnline -Url "https://contoso.sharepoint.com" -Interactive # 将本地文件上传到"Shared Documents"库 Add-PnPFile -Path "C:\Users\You\Documents\report.xlsx" -Folder "Shared Documents"
- Office 365 CLI: Cross-platform command-line tool (works on Windows, Mac, Linux). Great if you prefer lightweight CLI tools over PowerShell:
# 登录到Microsoft 365账号 o365 login # 上传文件到SharePoint o365 spo file add --webUrl https://contoso.sharepoint.com --folder "Shared Documents" --path "./local-files/team-photo.jpg"
- 手动UI上传: The simplest method for one-off files—just navigate to your SharePoint document library, click the "Upload" button, or drag-and-drop files directly into the browser window.
- 权限: 确保你的账号拥有目标文档库的编辑权限。对于API调用,要在Azure AD中给应用配置正确的权限(比如
Files.ReadWrite.All)。 - 大文件上传: 对于超过4MB的文件,SharePoint要求分块上传,需要使用
StartUpload、ContinueUpload和FinishUpload端点,而不是简单的add方法。 - 文件覆盖: 如果需要替换已存在的文件,一定要指定
overwrite=true,否则SharePoint会因文件名重复抛出错误。
内容的提问来源于stack exchange,提问作者Mahendran V M




