実現したいこと
Google Driveにあるファイルを指定したGoogle Driveのフォルダに分割アップロードしたいです。ソースコードではfetchを使っていますが、できればサービスにあるDrive APIを使って書きたいです。理由は調べていたらResumable uploadというのを使ってもできるという記事を見つけたのでできたらいいなと思っております。
前提
GAS (Google Apps Script)でファイルを分割アップロードする機能を作っています。
fetchをしていたところ、以下のエラーが出ました。
発生している問題・エラーメッセージ
Exception: Request failed for https://www.googleapis.com returned code 400. Truncated server response: Invalid request. There were 5242881 byte(s) (or more) in the request body. There should have been 5242880 byte(s) (starting at offset 0 and endin... (use muteHttpExceptions option to examine full response) test2 @ コード.gs:58
該当のソースコード
GAS
1function test2() { 2 const file = DriveApp.getFileById("###file id###"); 3 const file_size = file.getSize(); 4 const chunk_size = 1024 * 1024 * 5; 5 const chunks = Math.ceil(file_size / chunk_size); 6 const folder = DriveApp.getFileById(ScriptApp.getScriptId()).getParents().next(); 7 let upload_url = UrlFetchApp.fetch("https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable", { 8 method: "POST", 9 headers: { 10 "Authorization": `Bearer ${ScriptApp.getOAuthToken()}`, 11 "Content-Type": "application/json", 12 "X-Upload-Content-Type": file.getMimeType(), 13 "X-Upload-Content-Length": file_size 14 }, 15 payload: JSON.stringify({ 16 title: file.getName(), 17 mimeType: file.getMimeType() 18 }) 19 }).getHeaders()["Location"]; 20 21 for(let i = 0; i < chunks; i++) { 22 const start_byte = i * chunk_size; 23 const end_byte = Math.min(start_byte + chunk_size, file_size); 24 const chunk_blob = UrlFetchApp.fetch(`https://www.googleapis.com/drive/v3/files/${file.getId()}?alt=media`, { 25 method: "GET", 26 headers: { 27 Authorization: `Bearer ${ScriptApp.getOAuthToken()}`, 28 Range: `bytes=${start_byte}-${end_byte}` 29 } 30 }).getBlob(); 31 32 console.log(i) 33 /*const options = { 34 method: "PUT", 35 headers: { 36 "Authorization": `Bearer ${ScriptApp.getOAuthToken()}`, 37 "Content-Length": chunk_blob.getBytes().length, 38 "Content-Range": `bytes ${start_byte}-${end_byte - 1}/${file_size}` 39 }, 40 payload: chunk_blob.getBytes() 41 };*/ 42 const options = { 43 method: "PUT", 44 headers: { 45 "Authorization": `Bearer ${ScriptApp.getOAuthToken()}`, 46 "Content-Range": `bytes ${start_byte}-${end_byte - 1}/${file_size}` 47 }, 48 payload: chunk_blob.getBytes() 49 }; 50 51 UrlFetchApp.fetch(upload_url, options); 52 } 53}
何バイトアップロードしようとしているのか指定しているサイズ等確認してみましたか?
確認してきました。サイズは479409676バイトです。ファイルの型はmp4です。
>サイズは479409676バイトです
それはアップロードしようとしている全体のサイズですよね?
エラーメッセージを読みましたか?
エラーメッセージには
>There were 5242881 byte(s) (or more) in the request body. There should have been 5242880 byte(s)
とあります。
ヘッダに指定したサイズと実際にpayloadに指定したバイト配列のサイズは確認しましたか?

回答1件
あなたの回答
tips
プレビュー