* https://developers.google.com/drive/api/guides/manage-uploads * https://stackoverflow.com/questions/65181932/how-i-can-upload-file-to-google-drive-with-google-drive-api
(
key: string,
content: ArrayBuffer,
mtime: number,
ctime: number
)
| 487 | * https://stackoverflow.com/questions/65181932/how-i-can-upload-file-to-google-drive-with-google-drive-api |
| 488 | */ |
| 489 | async writeFile( |
| 490 | key: string, |
| 491 | content: ArrayBuffer, |
| 492 | mtime: number, |
| 493 | ctime: number |
| 494 | ): Promise<Entity> { |
| 495 | if (key.endsWith("/")) { |
| 496 | throw Error(`should not call writeFile on ${key}`); |
| 497 | } |
| 498 | |
| 499 | await this._init(); |
| 500 | |
| 501 | const contentType = |
| 502 | mime.contentType(mime.lookup(key) || DEFAULT_CONTENT_TYPE) || |
| 503 | DEFAULT_CONTENT_TYPE; |
| 504 | |
| 505 | let parentID: string | undefined = undefined; |
| 506 | let parentFolderPath: string | undefined = undefined; |
| 507 | |
| 508 | // "xxx" => [] |
| 509 | // "xxx/yyy/zzz.md" => ["xxx", "xxx/yyy"] |
| 510 | const folderLevels = getFolderLevels(key); |
| 511 | if (folderLevels.length === 0) { |
| 512 | // root |
| 513 | parentID = this.baseDirID; |
| 514 | parentFolderPath = ""; |
| 515 | } else { |
| 516 | parentFolderPath = `${folderLevels[folderLevels.length - 1]}/`; |
| 517 | if (!(parentFolderPath in this.keyToGDEntity)) { |
| 518 | throw Error( |
| 519 | `parent of ${key}: ${parentFolderPath} is not created before??` |
| 520 | ); |
| 521 | } |
| 522 | parentID = this.keyToGDEntity[parentFolderPath].id; |
| 523 | } |
| 524 | |
| 525 | const fileItself = key.split("/").pop()!; |
| 526 | |
| 527 | if (content.byteLength <= 5 * 1024 * 1024) { |
| 528 | const formData = new FormData(); |
| 529 | const meta: any = { |
| 530 | name: fileItself, |
| 531 | modifiedTime: unixTimeToStr(mtime, true), |
| 532 | createdTime: unixTimeToStr(ctime, true), |
| 533 | parents: [parentID], |
| 534 | }; |
| 535 | formData.append( |
| 536 | "metadata", |
| 537 | new Blob([JSON.stringify(meta)], { |
| 538 | type: "application/json; charset=UTF-8", |
| 539 | }) |
| 540 | ); |
| 541 | formData.append("media", new Blob([content], { type: contentType })); |
| 542 | |
| 543 | const res = await fetch( |
| 544 | "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=kind,fileExtension,md5Checksum,mimeType,parents,size,spaces,id,name,trashed,createdTime,modifiedTime,quotaBytesUsed,originalFilename,fullFileExtension,sha1Checksum,sha256Checksum", |
| 545 | { |
| 546 | method: "POST", |
nothing calls this directly
no test coverage detected