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

如何通过REST API上传HTML并转换为Google Docs文档

解决方法

要创建带HTML内容的Google Docs文档,不能直接通过application/vnd.google-apps.document类型的请求传HTML数据,需要先上传HTML格式的文件,再让Google Drive自动转换为Docs格式。具体操作如下:

核心思路

  • 上传时指定源文件的MIME类型为text/html,同时设置convert=true参数让Drive自动转换为Google Docs格式。
  • 使用multipart/form-data格式上传文件内容,而非通过JSON payload传递。

代码示例

使用Superagent实现

const superagent = require('superagent');
const FormData = require('form-data');

async function createDocFromHtml(token) {
  const formData = new FormData();
  // 添加文档标题元数据
  formData.append('metadata', JSON.stringify({
    name: 'Some title'
  }), { contentType: 'application/json' });
  // 添加HTML内容,指定源MIME类型
  formData.append('file', '<a href="https://google.com">Google</a>', { contentType: 'text/html' });

  const { body } = await superagent
    .post('https://www.googleapis.com/upload/drive/v3/files')
    .query({ convert: true }) // 启用格式转换
    .send(formData)
    .set('Authorization', `Bearer ${token}`)
    .set('Content-Type', `multipart/form-data; boundary=${formData.getBoundary()}`);

  console.log('创建的文档信息:', body);
  return body;
}

使用Axios实现

const axios = require('axios');
const FormData = require('form-data');

async function createDocFromHtml(token) {
  const formData = new FormData();
  formData.append('metadata', JSON.stringify({
    name: 'Some title'
  }), { contentType: 'application/json' });
  formData.append('file', '<a href="https://google.com">Google</a>', { contentType: 'text/html' });

  const response = await axios.post(
    'https://www.googleapis.com/upload/drive/v3/files?convert=true',
    formData,
    {
      headers: {
        'Authorization': `Bearer ${token}`,
        ...formData.getHeaders()
      }
    }
  );

  console.log('创建的文档信息:', response.data);
  return response.data;
}

关键说明

  • 必须使用上传接口(https://www.googleapis.com/upload/drive/v3/files)而非普通文件创建接口,才能支持文件内容上传和格式转换。
  • convert=true参数会让Google Drive将上传的HTML文件自动转换为Google Docs格式,转换后的文档会保留HTML的基本格式(如链接、文本样式等)。
  • 若不需要保留原HTML文件,可在转换完成后删除源文件,或通过设置fields参数只获取目标Docs的信息。

内容的提问来源于stack exchange,提问作者Gustavo Mendonça

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 11:05:39