【问题标题】:Uploading file via Google Drive API with simple upload (uploadType=media)通过简单上传的 Google Drive API 上传文件 (uploadType=media)
【发布时间】:2021-11-30 08:20:21
【问题描述】:

我正在使用 google API,我想将文件从 UI 下载到我的 google 驱动器。

正如我在 google drive API 文档 here 中找到的,我想使用简单的导入。

目前我的 onChange 输入事件有这样的代码。

const onLoadFile = async (e: { target: { files: any } }) => {
  const fileData = e.target.files[0];

  //gapi request
  uploadFile(body);
  return null;
};

上传文件:

const uploadFile = async (body: string) => {
  const result = await gapiRequest({
    path: `${ENDPOINT}/upload/drive/v3/files`,
    method: 'POST',
    body,
  });
  setUploadFileData(result);
};

gapiRequest:

const gapiRequest = async (options: gapi.client.RequestOptions): Promise<any> =>
  new Promise<any>((resolve, reject) =>
    gapi.client.request(options).execute((res) => {
        resolve(res);
        if (!res) {
        reject(res);
      }
  })
);

我需要知道我需要为这样的请求创建哪个请求正文。

【问题讨论】:

    标签: javascript reactjs file google-api google-drive-api


    【解决方案1】:

    请求body 应该包含一个包含元数据和文件的form,如下所示:

    const metadata = {
        "name": "yourFilename",
        "mimeType": "text/plain", // whatever is appropriate in your case
        "parents": ["folder id or 'root'"], // Google Drive folder id
    };
    
    const form = new FormData();
    form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
    form.append('file', file); // file could be a blob or similar
    

    您可能还需要将uploadType 参数添加到您的path 属性。 multipart 值甚至适用于简单的上传。

    参见此处:https://stackoverflow.com/a/68595887/7821823

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-11
      • 1970-01-01
      相关资源
      最近更新 更多