Microsoft Graph上传API频繁出现504网关超时错误
Hey there, let's walk through how to fix this persistent 504 timeout issue you're facing when uploading images to OneDrive using the Microsoft Graph API. First, let's recap the details you shared:
You're using this API endpoint for uploads:PUT https://graph.microsoft.com/v1.0/users/{userId}/drive/items/{rootFolderId}/{folderPath}/{fileName}:/content
And the error response you're getting:
504 Gateway Timeout
{ "error": { "code": "UnknownError", "message": "", "innerError": { "request-id": "9709847a-36d4-42f2-90dd-4c37094caead", "date": "2018-05-16T12:18:37" } } }
Here are actionable steps to diagnose and resolve the problem:
Validate your request path and parameters
Double-check that all placeholders like{userId},{rootFolderId},{folderPath}, and{fileName}are replaced with valid, correctly formatted values. Pay extra attention to{folderPath}—it should use forward slashes to separate folders, and any special characters (spaces, ampersands, etc.) in paths or filenames need to be URL-encoded. For example, a folder named "My Photos" should becomeMy%20Photos.Adjust client-side timeout settings
A 504 error often means the gateway is waiting too long for the backend to respond, which could happen if your client cuts off the request too early. If you're uploading large images, increase your client's timeout threshold to at least 300 seconds (5 minutes) to give the transfer enough time to complete.Switch to chunked uploads for large files
If your images are larger than 4MB, the direct PUT request can be unstable and prone to timeouts. Instead, use Microsoft Graph's chunked upload workflow:- Create an upload session with a
POSTrequest to/drive/items/{item-id}/createUploadSession - Upload file chunks using
PUTrequests to the session URL - Finalize the upload once all chunks are sent
This approach reduces the load per request and minimizes timeout risks.
- Create an upload session with a
Verify permissions and authentication
Ensure your application has the correct API permissions (likeFiles.ReadWrite.Allor a scoped permission for the target drive) and that your access token is valid and not expired. Sometimes permission issues manifest as unexpected timeouts instead of explicit permission errors.Check Microsoft 365 service health
Rarely, temporary outages or high load on Microsoft's end can cause timeouts. Head to the Microsoft 365 Admin Center and check the service health dashboard to confirm OneDrive and Microsoft Graph services are running normally.Implement retry logic with exponential backoff
504 errors can sometimes be transient due to network blips or peak service load. Add a retry mechanism that waits longer between each attempt (e.g., 1s, 2s, 4s, up to 5 retries) to give the service time to recover.
内容的提问来源于stack exchange,提问作者Kratika Saxena

