通过Google Drive API Javascript将图像从URL上传到Google Drive

通过Google Drive API Javascript将图像从URL上传到Google Drive,javascript,file-upload,google-drive-api,Javascript,File Upload,Google Drive Api,我是Javascript新手,如果你觉得我的问题很蹩脚,我很抱歉。我想从我的网站上传一张图片到我的谷歌硬盘。我已经成功实现了身份验证和文件夹创建部分,但我对上传过程感到困惑。 假设这是我在Google Drive中创建文件夹的代码: function createFolder(folderName) { var parentId = 'xxxxxxx';//some parentId of a folder under which to create the new folder var

我是Javascript新手,如果你觉得我的问题很蹩脚,我很抱歉。我想从我的网站上传一张图片到我的谷歌硬盘。我已经成功实现了身份验证和文件夹创建部分,但我对上传过程感到困惑。
假设这是我在Google Drive中创建文件夹的代码:

function createFolder(folderName) {
  var parentId = 'xxxxxxx';//some parentId of a folder under which to create the new folder
  var fileMetadata = {
    'name' : folderName,
    'mimeType' : 'application/vnd.google-apps.folder',
    'parents': [parentId]
  };
  gapi.client.drive.files.create({
    resource: fileMetadata,
  }).then(function(response) {
    switch(response.status){
      case 200:
      var file = response.result;
      console.log('Created Folder Id: ', file.id);
      uploadImage(file.id);
      break;
      default:
      console.log('Error creating the folder, '+response);
      break;
    }
  });
}
现在我想从这个url上传我的图片:
https://xxxxxx.com
从上层响应(
file.id
)进入新创建的文件夹

这是我在GoogleAPI文档中得到的,但是我应该把我的url放在哪里

function uploadImage(folderId) {
  var fileMetadata = {
    'name': 'photo.jpg',
    parents: [folderId]
  };
  var media = {
    mimeType: 'image/jpeg',
    body: fs.createReadStream('files/photo.jpg')
  };
  drive.files.create({
    resource: fileMetadata,
    media: media,
    fields: 'id'
  }, function (err, file) {
    if (err) {
      // Handle error
      console.error(err);
    } else {
      console.log('File Id: ', file.id);
    }
  });
}   

提前非常感谢。

尝试使用以下片段上载照片文件:

// download file from website 
const http  = require('https')
const fs    = require('fs')

let file    = fs.createWriteStream('Photo001.jpg')
let request = http.get(
    'https://ssl.gstatic.com/ui/v1/icons/mail/rfr/logo_gmail_lockup_default_2x.png', 
    (response) => {
        response.pipe(file)
    })

// upload file to Google Drive
let fileMetadata = {
  'name'    : 'Photo001',
  'mimeType': 'image/jpeg'
}

let media = {
  mimeType  : 'image/jpeg',
  body      : fs.createReadStream('Photo001.jpeg')
}

function uploadFile(auth){

  const drive = google.drive({version: 'v3', auth})

  drive.files.create({
    resource: fileMetadata,
    media   : media,
    fields  : 'id'
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err)
  })

}
文档

    • 我相信你的目标如下

      • 您希望从URL下载一个文件,并使用Javascript将下载的文件上载到Google Drive
      • 在您的情况下,您的
        gapi.client
        可用于将文件上载到Google Drive
      修改点:
      • 不幸的是,在当前阶段,
        gapi.client.drive.files.create仍然无法发送包含内容的请求。因此,在本例中,我建议使用
        fetch
        作为解决方法。使用
        fetch
        时,可以使用
        多部分/表单数据
        请求文件内容和元数据
      • 在此解决方案中,访问令牌是从
        gapi.client
        使用的。因此,此脚本假定您的
        gapi.client
        可用于上载文件。请小心这个
      修改脚本:
      • 运行此脚本时,可以在控制台上看到以下结果。(当URL是Jpeg图像文件的直接链接时。)

      注:
      • 在这种情况下,将使用
        uploadType=multipart
        。因此,最大文件大小为5MB。请小心这个。当您想使用超过5 MB的数据时,请检查可恢复上传
      参考资料:
      补充: 为了避免与CORS相关的错误,作为另一种方法,我建议将Web应用程序用作包装器。在本例中,客户端是Javascript。这个Javascript可以在Google之外使用

      用法: 请执行以下流程

      1.创建谷歌应用程序脚本的新项目。 Web应用程序的示例脚本是Google应用程序脚本。因此,请创建一个谷歌应用程序脚本项目

      如果要直接创建,请访问。在这种情况下,如果您没有登录Google,则会打开登录屏幕。所以请登录谷歌。这样,谷歌应用程序脚本的脚本编辑器就打开了

      2.准备脚本。 请将以下脚本(Google Apps脚本)复制并粘贴到脚本编辑器。此脚本用于Web应用程序

      服务器端:谷歌应用程序脚本 此脚本用于Web应用程序。在本例中,Web应用程序用作包装器

      function doGet(e) {
        const imageUrl = e.parameter.imageUrl;
        const res = UrlFetchApp.fetch(imageUrl);
        if (res.getResponseCode() != 200) throw new Error("Image couldn't be retrieved.");
        const blob = res.getBlob();
        const file = DriveApp.getFolderById(e.parameter.folderId).createFile(blob.setName(e.parameter.filename));
        const obj = {id: file.getId(), name: file.getName(), mimeType: file.getMimeType()};
        return ContentService.createTextOutput(JSON.stringify(obj)).setMimeType(ContentService.MimeType.JSON);
      }
      
      3.部署Web应用程序。
    • 在脚本编辑器上,通过“发布”->“部署为web应用”打开对话框
    • 选择“我”以执行应用程序:“”。
      • 这样,脚本将作为所有者运行
    • 为有权访问应用程序的用户选择“任何人,甚至匿名”
    • 单击“部署”按钮作为新的“项目版本”
    • 自动打开“需要授权”对话框。
    • 单击“查看权限”
    • 选择自己的帐户
    • 单击“此应用未验证”处的“高级”
    • 单击“转到####项目名称###(不安全)”
    • 单击“允许”按钮
    • 单击“确定”
    • 复制Web应用程序的URL。就像
      https://script.google.com/macros/s/###/exec
      • 当您修改Google Apps脚本时,请重新部署为新版本。这样,修改后的脚本将反映到Web应用程序中。请注意这一点。
    • 4.将文件从客户端上载到服务器端。 客户端:HTML和Javascript 请将Web应用的URL设置为以下脚本。请设置文件名和文件夹ID

      const imageUrl = "###"; // Please set the URL of image.
      
      const url = "https://script.google.com/macros/s/###/exec"; // Please set the URL of Web Apps.
      const qs = new URLSearchParams({
        imageUrl: imageUrl,
        filename: "sample filename",
        folderId: "###", // Please set folder ID.
      });
      fetch(`${url}?${qs}`).then((res) => res.json()).then(console.log).catch(console.log);
      
      结果: 当运行上述脚本时,将返回以下值。您可以在控制台上看到返回的值

      {
        "id": "###",
        "name": "###",
        "mimeType": "###"
      }
      
      注:
      • 修改Web应用脚本时,请将Web应用重新部署为新版本。这样,最新的脚本就会反映到Web应用程序中。请注意这一点。
      参考资料:

      您的上层和下层脚本似乎分别是Javascript和Node.js。很遗憾,我不能理解你的问题。我为此道歉。我可以问一下你当前问题的细节和你的目标吗?@Tanaike谢谢你的评论。让我再解释一下我的问题。我在某个url上有一个图像,比如()。所以我想使用GoogleDrive API将该图像从该url上传到我的GoogleDrive。我想将该图像保存/上传到一个特定的文件夹中,我还想从客户端创建该文件夹。因此,在这里,我在成功验证后在父文件夹下创建了该文件夹(本文代码部分的第一部分)。现在是时候将该url()中的图像上载/保存到新创建的文件夹中的Google驱动器中了。但是,当我在谷歌API官方文档中搜索时,我发现了这段代码(我在文章中代码部分的第二部分),我不知道如何附加我的url(),以便将其上载到我的谷歌驱动器。因此,在谷歌API的官方文档中(我代码的第二部分)我在var
      fileMetadata
      下看到了
      name:photo.jpg
      ,但我有url而不是任何图像名称。那么,我如何用这个函数附加我的url,以便将其上传到我的谷歌硬盘上呢。谢谢看看我的答案,测试一下,让我知道你的结果谢谢你的回答。但是我会把我的图片URL的值附加到哪里呢?正如我所说的
      const imageUrl = "###"; // Please set the URL of image.
      
      const url = "https://script.google.com/macros/s/###/exec"; // Please set the URL of Web Apps.
      const qs = new URLSearchParams({
        imageUrl: imageUrl,
        filename: "sample filename",
        folderId: "###", // Please set folder ID.
      });
      fetch(`${url}?${qs}`).then((res) => res.json()).then(console.log).catch(console.log);
      
      {
        "id": "###",
        "name": "###",
        "mimeType": "###"
      }