You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript从Strapi上传文件至Google Drive及相关文档查询

从Strapi上传文件至Google Drive的JavaScript实现方案

一、前置准备

  • 启用Google Drive API:在Google Cloud控制台创建项目,搜索并启用Drive API,创建服务账号并下载JSON格式的密钥文件。
  • 配置权限:在Google Drive中创建目标文件夹,将服务账号的邮箱(密钥文件里的client_email字段)添加为该文件夹的编辑者。
  • Strapi端安装依赖:在Strapi项目根目录执行npm install googleapis或yarn add googleapis。

二、核心实现步骤

1. 创建Google Drive工具类

在Strapi项目的src/utils目录下新建google-drive.js,封装上传逻辑:

const { google } = require('googleapis');
const fs = require('fs');
const path = require('path');

// 加载服务账号密钥
const auth = new google.auth.GoogleAuth({
  keyFile: path.join(__dirname, '../../google-service-account-key.json'), // 替换为你的密钥文件实际路径
  scopes: ['https://www.googleapis.com/auth/drive.file'],
});

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

// 上传文件到指定Google Drive文件夹
async function uploadFileToDrive(filePath, fileName, folderId) {
  try {
    const fileMetadata = {
      name: fileName,
      parents: [folderId], // 替换为你的目标文件夹ID
    };

    const media = {
      mimeType: 'application/octet-stream', // 可根据文件类型调整,比如图片用image/jpeg、文档用application/pdf
      body: fs.createReadStream(filePath),
    };

    const response = await drive.files.create({
      resource: fileMetadata,
      media: media,
      fields: 'id',
    });

    return response.data.id;
  } catch (error) {
    console.error('上传至Google Drive失败:', error);
    throw error;
  }
}

module.exports = { uploadFileToDrive };

2. 在Strapi中触发上传逻辑

可以通过生命周期钩子或自定义控制器来触发上传:

方式一:使用生命周期钩子(推荐)

在Strapi默认的文件上传内容类型(upload)的生命周期文件src/api/upload/content-types/upload/lifecycles.js中添加:

const { uploadFileToDrive } = require('../../../../utils/google-drive');

module.exports = {
  async afterCreate(event) {
    const { result } = event;
    // Strapi本地存储的文件路径,默认是public/uploads下的哈希+扩展名文件
    const localFilePath = `./public/uploads/${result.hash}${result.ext}`;
    try {
      const driveFileId = await uploadFileToDrive(localFilePath, result.name, '你的目标文件夹ID');
      // 可选:将Google Drive文件ID保存到Strapi的文件记录元数据中
      await strapi.db.query('plugin::upload.file').update({
        where: { id: result.id },
        data: { metadata: { ...result.metadata, driveFileId } },
      });
    } catch (err) {
      console.error('处理文件上传至Drive失败:', err);
    }
  },
};

方式二:自定义控制器(手动触发场景)

如果需要手动触发上传,可以在src/api/upload/controllers/upload.js中添加自定义方法:

const { uploadFileToDrive } = require('../../../utils/google-drive');

module.exports = {
  async uploadToDrive(ctx) {
    const { fileId } = ctx.params;
    const file = await strapi.db.query('plugin::upload.file').findOne({ where: { id: fileId } });
    if (!file) {
      return ctx.badRequest('文件不存在');
    }
    const localFilePath = `./public/uploads/${file.hash}${file.ext}`;
    try {
      const driveFileId = await uploadFileToDrive(localFilePath, file.name, '你的目标文件夹ID');
      return ctx.send({ driveFileId });
    } catch (err) {
      return ctx.internalServerError('上传至Google Drive失败');
    }
  },
};

三、相关文档参考

  • Strapi端:官方文档包含自定义工具类、生命周期钩子、文件上传系统的详细说明,可直接在Strapi后台的文档入口查看对应模块。
  • Google Drive端:Google Drive API官方文档有文件上传、权限配置的完整指南,重点关注files.create接口的参数与权限说明。
  • 社区资源:Strapi社区论坛中有不少用户分享的适配不同版本的实现案例,搜索关键词即可找到参考。

内容的提问来源于stack exchange,提问作者Virendra Maheta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:27:49