How to save images from a web URL to Google Drive using JavaScript and the Drive API?

I’m a JavaScript newbie trying to figure out how to save images from my website to Google Drive. I’ve got the authentication and folder creation working, but I’m stuck on the image upload part.

Here’s my code for making a new folder in Google Drive:

function makeNewFolder(name) {
  let parentFolder = 'abc123'; // ID of parent folder
  let folderInfo = {
    'name': name,
    'mimeType': 'application/vnd.google-apps.folder',
    'parents': [parentFolder]
  };
  gapi.client.drive.files.create({
    resource: folderInfo,
  }).then(function(result) {
    if (result.status === 200) {
      let newFolder = result.result;
      console.log('New folder ID:', newFolder.id);
      saveImageToFolder(newFolder.id);
    } else {
      console.log('Folder creation failed:', result);
    }
  });
}

Now I want to save an image from a URL to this new folder. The Drive API docs show this:

function saveImageToFolder(folderId) {
  let fileInfo = {
    'name': 'image.jpg',
    parents: [folderId]
  };
  let imageData = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/image.jpg')
  };
  // More code here...
}

But I’m not sure where to put my image URL in this code. Can someone help me out? Thanks!

Having worked on a similar project, I can offer some advice. The key is to use the Fetch API to retrieve the image data from the URL before uploading it to Google Drive. Here’s a simplified approach:

  1. Fetch the image from the URL
  2. Create a Blob from the response
  3. Use the Drive API to upload the Blob

Here’s a code snippet to illustrate:

async function saveImageToFolder(folderId, imageUrl) {
  const response = await fetch(imageUrl);
  const blob = await response.blob();
  
  const fileMetadata = {
    name: 'image.jpg',
    parents: [folderId]
  };
  
  const form = new FormData();
  form.append('metadata', new Blob([JSON.stringify(fileMetadata)], {type: 'application/json'}));
  form.append('file', blob);

  try {
    const result = await gapi.client.request({
      path: '/upload/drive/v3/files',
      method: 'POST',
      params: {uploadType: 'multipart'},
      body: form
    });
    console.log('Image uploaded successfully:', result);
  } catch (error) {
    console.error('Error uploading image:', error);
  }
}

This approach should work for your use case. Remember to handle errors and check the response.

hey, try using the fetch api to get the image as a blob then upload it.

let res = await fetch(url);
let blob = await res.blob();

hope this helps! lmk if u need more info.

I’ve tackled a similar project before, and I can share some insights. Instead of using fs.createReadStream, which is for local files, you’ll need to fetch the image from the URL first. Here’s a rough outline of how you might approach this:

  1. Use the Fetch API to get the image data from the URL.
  2. Convert the response to a Blob.
  3. Use the Google Drive API to upload the Blob.

Here’s a snippet to get you started:

async function saveImageToFolder(folderId, imageUrl) {
  const response = await fetch(imageUrl);
  const blob = await response.blob();
  
  const fileMetadata = {
    name: 'image.jpg',
    parents: [folderId]
  };
  
  const form = new FormData();
  form.append('metadata', new Blob([JSON.stringify(fileMetadata)], {type: 'application/json'}));
  form.append('file', blob);

  await gapi.client.request({
    path: '/upload/drive/v3/files',
    method: 'POST',
    params: {uploadType: 'multipart'},
    body: form
  });
}

Remember to handle errors and check the response. This should get you on the right track!