Uploading Movie File on Google Drive to YouTube using Google Apps Script

Gists

Uploading Movie File on Google Drive to YouTube using Google Apps Script

This is a sample script for uploading a movie file on Google Drive to YouTube using Google Apps Script.

Before you use these scripts, please enable YouTube API at Advanced Google services. Ref

Sample script 1

This sample script uses YouTube API at Advanced Google services.

function myFunction() {
  const fileId = "###"; // Please set the file ID of movie file on the Google Drive.

  const res = YouTube.Videos.insert(
    { snippet: { title: "sample title", description: "sample description" } },
    ["snippet"],
    DriveApp.getFileById(fileId).getBlob()
  );
  console.log(res);
}

Sample script 2

This sample script requests to the endpoint of YouTube API with UrlFetchApp by creating the request body. This script requests with multipart/form-data.

function myFunction() {
  const fileId = "###"; // Please set the file ID of movie file on the Google Drive.

  const metadata = {
    snippet: { title: "sample title", description: "sample description" },
  };
  const url =
    "https://www.googleapis.com/upload/youtube/v3/videos?part=snippet";
  const file = DriveApp.getFileById(fileId);
  const boundary = "xxxxxxxxxx";
  let data = "--" + boundary + "\r\n";
  data += "Content-Type: application/json; charset=UTF-8\r\n\r\n";
  data += JSON.stringify(metadata) + "\r\n";
  data += "--" + boundary + "\r\n";
  data += "Content-Type: " + file.getMimeType() + "\r\n\r\n";
  const payload = Utilities.newBlob(data)
    .getBytes()
    .concat(file.getBlob().getBytes())
    .concat(Utilities.newBlob("\r\n--" + boundary + "--").getBytes());
  const options = {
    method: "post",
    contentType: "multipart/form-data; boundary=" + boundary,
    payload: payload,
    headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
    muteHttpExceptions: true,
  };
  const res = UrlFetchApp.fetch(url, options).getContentText();
  console.log(res);

  // YouTube.Videos.insert() // This comment line is used for automatically detecting the required scope.
}

Note

References

 Share!