如何在Angular中通过POST请求创建Google Drive文件?参数设置遇阻
Fixing the File Name Issue When Uploading to Google Drive in Angular
Hey there! Let's break down why your file name isn't being set correctly when uploading to Google Drive, and fix it step by step.
The Root of the Problem
When using uploadType=multipart for Google Drive's API, you can't just pass a plain JSON object as the request body. Multipart uploads require a specific structure: they split the request into two parts—metadata (like the file name) and the actual file content—formatted as multipart/form-data. Your current code is sending JSON directly, which Google's API doesn't parse correctly for this upload type.
The Fixed Implementation
Here's how to adjust your DriveService to properly set the file name and handle multipart uploads:
@Injectable({ providedIn: 'root' }) export class DriveService { constructor(private http: HttpClient) { } // Helper to get auth headers (avoids recreating them on every call) private getAuthHeaders(): HttpHeaders { const token = localStorage.getItem('tokenGoogle'); return new HttpHeaders() .set('Authorization', `Bearer ${token}`) .set('Accept', 'application/json'); // Don't manually set Content-Type—FormData handles this automatically } creaFileDrive(nome: string): Observable<DriveResultFile> { const formData = new FormData(); // 1. Add the metadata part (JSON string with file name) const fileMetadata = JSON.stringify({ name: nome, // Use the passed nome parameter instead of hardcoding // Optional: Add other metadata like mimeType, parent folder IDs, etc. }); formData.append('metadata', fileMetadata, { type: 'application/json' }); // 2. Add the file content part // If you're creating an empty file, use an empty Blob const emptyFile = new Blob([], { type: 'application/octet-stream' }); formData.append('file', emptyFile); // If uploading an actual file from the user's device, replace with: // formData.append('file', userSelectedFile); const apiUrl = 'https://www.googleapis.com/upload/drive/v3/files?key=AIzXXXXXXXXXXXXXXXXXX&uploadType=multipart'; return this.http.post<DriveResultFile>(apiUrl, formData, { headers: this.getAuthHeaders() }); // The map operator was redundant here—we can return the observable directly } }
Key Changes Explained
- Use FormData for Multipart Requests: This automatically formats the request into the
multipart/form-datastructure Google expects, including the correct boundary markers. - Separate Metadata and File Content: The metadata is serialized to a JSON string and marked as
application/json, so Google's API can parse thenamefield correctly. - Skip Manual Content-Type: Manually setting
Content-Type: application/jsonbreaks the multipart structure—let FormData handle this for you. - Optional: Simplify for Empty Files: If you're just creating an empty file (no actual content to upload), you can skip multipart entirely and use a standard POST request:
creaEmptyFileDrive(nome: string): Observable<DriveResultFile> { const apiUrl = 'https://www.googleapis.com/drive/v3/files?key=AIzXXXXXXXXXXXXXXXXXX'; const metadata = { name: nome }; return this.http.post<DriveResultFile>(apiUrl, metadata, { headers: this.getAuthHeaders() }); }
Quick Checks to Ensure Success
- Make sure your Google Drive API token has the
https://www.googleapis.com/auth/drivescope (required to create files). - Verify the token is not expired (localStorage tokens can expire—you may need to handle refresh logic).
内容的提问来源于stack exchange,提问作者Edoardo
相关产品推荐
相关产品推荐

